0

So I have to create a function that will average the numbers inputted by the user in an array which can go up to 10 numbers, but could be stopped anywhere between the first input and the tenth by the user inputting -1

i'm unsure whether its similar to finding the highest number which i've done

What I have going right now is but I have no clue on how to get it to average the numbers since its not going to be divided by a set number

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;
 }

EDIT: To clarify, the max number is results a user can enter is 10 thats why it goes up to 10.

4

4 回答 4

0

试试这个代码...

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;

}
于 2013-11-10T07:24:31.573 回答
0

您可以将迭代器用作计数器,并使用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;
}
于 2013-11-10T07:28:18.780 回答
0

下面的代码应该对你有用(尽管我可能在某处有一个错误)。秘密是 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. */
    }
}
于 2013-11-10T07:29:02.673 回答
0

我现在要做的是,但我不知道如何让它平均数字,因为它不会被设定的数字除以

您应该仅通过保留一个计数器来跟踪用户输入了多少数字。

然后你可以用它作为你的除数,并得到平均值。

于 2013-11-10T07:21:43.953 回答