函数在数组中求平均值
function to average in an array
所以我必须创建一个函数,该函数将平均用户在一个数组中输入的数字,该数组最多可以达到 10 个数字,但可以通过用户输入 -1 在第一个输入和第十个输入之间的任何地方停止
我不确定它是否类似于找到我所做的最高数字
我现在要做的是,但我不知道如何让它平均数字,因为它不会被设定的数字除以
cout << "The average of the results = " << calc_average(score) << "n";
cout << "The lowest of the results = " << find_lowest(score) << "n";
system("Pause");
}
double calc_average(double a[])
{
}
double find_highest(double a[])
{
double temp = 0;
for(int i=0;i<10;i++)
{
if(a[i]>temp)
temp=a[i];
}
return temp;
}
编辑:澄清一下,用户可以输入的最大数字是10,这就是为什么它上升到10。
我现在要做的是,但我不知道如何让它 平均数字,因为它不会除以设定的数字
您应该通过保留计数器来跟踪用户输入了多少个数字。
然后你可以用它作为你的除数,得到平均值。
试试这段代码...
double calc_average(double a[])
{
double fAverage = 0.0f;
double fCount = 0.0f;
double fTotal = 0.0f;
for(int i=0; i<10; i++)
{
if(a[i] < 0)
break;
fTotal += a[i];
fCount += 1.0f;
}
if( fCount > 0.0f )
fAverage = fTotal / fCount;
return fAverage;
}
您可以使用迭代器作为计数器和名为 avg
的变量来存储平均值。最后只需返回 avg
的值。
double find_highest(double a[])
{
double avg, temp = 0;
int i;
for(i=0; i<10; i++)
{
if(a[i]>temp)
temp += a[i];
}
avg = temp/i;
return avg;
}
以下代码应该适合您(尽管我可能在某处有一个错误)。秘密是 for 循环中的额外条件。
double calc_average(double a[])
{
int i;
float sum = 0.0;
for(i = 0; i < 10 && a[i] > -1; i++)
{
sum += a[i];
}
if(i > 0)
{
return sum / i;
}
else
{
return 0.0; /* Technically there is no average in this case. */
}
}
相关文章:
- 按平均值替换数组中的元素
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 浮点格式数组的平均值
- 使用动态数组求和和和求平均值
- 玩数字编程挑战(子数组的平均值)
- 查找数组最后 3 个数字的平均值
- C++数组的最大值、最小值、平均值函数
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 我需要以尺寸方式计算数组的平均值
- 计算数组中特定线的平均值并存储在另一个数组中
- 尝试在数组(C )中找到平均值时,获取-NAN(IND)输出
- 从数组中获取值并计算平均值,然后存储在数组中
- 如何在数组中的范围内添加所有数字?然后找到该范围的平均值
- C++数组,平均值(初学者)
- 数组元素的奇怪平均值
- c++中const数组的平均值模板
- C++计算2D数组中可变宽度数字的平均值
- 使用函数来查找数组C++的平均值
- 函数在数组中求平均值