计算平均值时重置总和

时间:2016-10-19 06:36:04

标签: c++ sum average

我有一个程序询问用户他们想要输入多少个测验,存储成绩,以及计算平均值。等级必须在0到100之间。但是,当我输入100以上的等级时,平均值是错误的。它不会重置总和。如果我输入120并且它提示我重新输入成绩,则在计算平均值时它仍然使用120。如何让它重置?

注意:我不想更改格式(例如使用while循环)。

#include <iostream>
using namespace std;
int main(){
    int n, i;
    float num[13], sum=0.0, average;
    cout << "Enter the numbers of quizzes from 1-13: ";
    cin >> n;

while (n < 1 || n > 13)
{
    cout << "You must enter a number from 1 - 13." << endl;
    cout << "Enter the number of quizzes you would like to input(1-13): “;
    cin >> n;

}


for(i=0; i<n; ++i)
  {
       cout << i+1 << ". Enter number: ";
       cin >> num[i];
       sum+=num[i];


    while (num[i] < 0 || num[i] > 100)
    {
    cout << “You must enter a number between 0 and 100. Re enter scores.”;
        cout << i+1 << ". Enter number: ";
        cin >> num[i];
    }
  }

   average=sum/n;
   cout << "Average = " << average;
   return 0;
}

2 个答案:

答案 0 :(得分:0)

只需将sum+=num[i]放在while (num[i] < 0 || num[i] > 100) ...循环后面!

这样您只能总结有效数字。

for(i=0; i<n; ++i)
{
   cout << i+1 << ". Enter number: ";
   cin >> num[i];
   //sum+=num[i]; remove here !!

   while (num[i] < 0 || num[i] > 100)
   {
    cout << “You must enter a number between 0 and 100. Re enter scores.”;
    cout << i+1 << ". Enter number: ";
    cin >> num[i];
   }

   sum+=num[i]; // <- insert here
}

答案 1 :(得分:0)

for(i=0; i<n; ++i)
  {
       cout << i+1 << ". Enter number: ";
       cin >> num[i];

    while (num[i] < 0 || num[i] > 100)
    {
    cout << “You must enter a number between 0 and 100. Re enter scores.”;
        cout << i+1 << ". Enter number: ";
        cin >> num[i];
    }
  }


   sum+=num[i];
   average=sum/n;
   cout << "Average = " << average;
   return 0;
}