C++另一种方法计算平均值
Calculating averages in another method C++
我将平均方法与main分开,main中的两个学生都调用该方法,但我不太确定如何通过这样做来计算平均值,有什么想法吗?
平均做两件事。 它计算学生分数的平均值,将整数平均值放在最后一个元素中,从而替换负数,然后返回在数组中找到的实际测试分数的数量。 数组中的哨兵是负数。
这是我的代码
#include <iostream>
using namespace std;
double average( int array[]); // function declaration (prototype)
int main()
{
int lazlo[] = {90, 80, 85, 75, 65, -10};
int pietra[] = { 100, 89, 83, 96, 98, 72, 78, -1};
int num;
num = average( lazlo );
cout << "lazlo took " << num << "tests. Average: " << lazlo[ num ] << endl;
num = average( pietra );
cout << "pietra took " << num << "test. Average: " << pietra[ num ] << endl;
}
double average( int array[])
{
// Average code
}
如果你真的想将一个 C 风格的数组作为唯一的参数传递给 average()
函数,你必须使用模板来推断它的大小:
#include <numeric>
#include <iostream>
using namespace std;
template <size_t N>
size_t count(int (&array)[N])
{
return N;
}
template <size_t N>
double average(int (&array)[N])
{
return std::accumulate(array, array + N, 0.0) / N;
}
int main()
{
int lazlo[] = {90, 80, 85, 75, 65, -10};
double num = average( lazlo );
cout << "lazlo took " << count(lazlo) << " tests. Average: " << average(lazlo) << endl;
}
当然,由于这是C++,因此最好使用std::vector
或std::array
来存储分数,在这种情况下,您可以这样做:
double average(const std::vector<int>& array)
{
return std::accumulate(array.begin(), array.end(), 0.0) / array.size();
}
现在我们终于知道了真正的分配:
"平均做两件事。它计算学生分数的平均值,将整数平均值放在最后一个元素中,从而替换负数,然后返回在数组中找到的实际测试分数的数量。数组中的哨兵是负数"
double average( int array[])
{
int i = 0;
int Total = 0;
while (array[i] >= 0) //Keep adding to total and increase i until negative value found.
Total += array[i++];
array[i] = Total / i;
return i; //Weird to return a double for this, but if that is the assignment...
}
相关文章:
- 计算平均值,不包括上次得分
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二叉搜索树C++中计算平均值
- 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?
- 我可以计算多线程数的平均值吗?
- 计算另一个图像像素满足条件的像素值的平均值
- 如何计算和显示C++中5个数字的平均值?
- 计算平均值:蒙版图像与投资回报率的不同结果
- 类型检测:使用variadic参数正确实现计算平均值的函数
- C 平均程序在循环时不计算n后不计算平均值
- C++ - 计算"for"函数中的平均值
- 计算用于CAFFE分类的HDF5数据集的平均值
- 如何使用多尺寸阵列计算C 中每个学生的平均值
- 如何计算结构阵列内的平均值
- 我需要以尺寸方式计算数组的平均值
- 我必须将 5 个数字放入一个数组中,而不是 cin 计算平均值并输出它,我做错了
- 我需要知道如何正确计算平均值和偏差
- 计算数组中特定线的平均值并存储在另一个数组中
- 如何使用不同的功能计算三个数字的总和,平均值和产物
- 浮点数组的中间模式平均值计算