函数在数组中求平均值

function to average in an array

本文关键字:平均值 数组 函数      更新时间:2023-10-16

所以我必须创建一个函数,该函数将平均用户在一个数组中输入的数字,该数组最多可以达到 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. */
    }
}