在一个函数中使用类的每个成员来计算平均值
Using each member of class within one function to calculate average
我有一个班,考试成绩为4分。测试1-测试4。我想创建一个名为mean的函数,它将计算课程中每次考试的平均值,并将其存储在mean数组中。但我似乎无法通过一个循环来实现这一点:
class Cstudent
{
public:
string firstName, lastName;
int test1, test2, test3, test4;
float average;
};
/* Here is the problem, the next time i go through the loop, i want to store the sum of
test2 in to sum[1] after already storing the total in to sum[0] for test 1 */
float mean(Cstudent section[], int n)
{
int sum[NUMBEROFEXAMS];
float mean[NUMBEROFEXAMS];
for(int i = 0; i < NUMBEROFEXAMS; i++)
for(int j = 0; j < n; j++){
sum[i] += section[j].test1;
}
}
将分数存储在数组中会更容易:
#include <array>
class Student
{
public:
string firstName, lastName;
std::array<int, 4> test;
float average;
};
然后你可以很容易地得到平均值:
#include <algorithm> // for std::accumulate
Student s = ....;
...
float avg = std::accumulate(s.test.begin(), s.test.end(), 1.0)/s.test.size();
你的意思是:
float mean(Cstudent section[], int n)
{
int sum[NUMBEROFEXAMS];
float mean[NUMBEROFEXAMS];
for(int i = 0; i < NUMBEROFEXAMS; i+=4)
for(int j = 0; j < n; j++){
sum[i] += section[j].test1;
sum[i+1] += section[j].test2;
sum[i+2] += section[j].test3;
sum[i+3] += section[j].test4;
}
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 计算数组c++的平均值
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 子构造函数无法识别基类的成员:平均值,西格玛"is not a nonstatic data member or base class"
- 在一个函数中使用类的每个成员来计算平均值