困惑于如何摆脱没有哨兵价值的无限循环

时间:2014-03-03 00:02:59

标签: c++ visual-studio-2010

我只能使用 while循环。我将提示用户输入他们的名字和姓名以及考试次数。然后我将使用while循环来总结和平均考试。 注意每个测试分数为100。

我进入了一个无限循环,但我不知道除了0之外这个循环会变成什么值。

这是我的代码:

#include <iostream>
#include <string>
#include <iomanip>


using namespace std;

int main()
{
string fname, lname;
int tests;
int test = 100;
double test_avg;

cout << "Please enter your first and last name." << endl;
cin >> fname >> lname;

cout << "Please enter the number of exams you have taken." << endl;
cin >> tests;

while( tests > 1 )
{
    test_avg = (test * tests) / tests;
    cout << setprecision(1) << showpoint << fixed;
    cout << fname << ' ' << lname << ' ' << test_avg << "%" << endl;
    tests = 0;

}

return 0;
}

1 个答案:

答案 0 :(得分:1)

“......我要使用while循环并平均考试”

如果你没有询问一个人每个考试的分数,平均值将是100,我认为这是最大分数。

对于一个循环,总是问自己 - 循环什么时候结束?我会说,当一个人停止输入结果时。

您可以按如下方式组织输入:

int scores=0;
int cnt = 0;
while (true) {
    cout << "Please enter the scores of the exams you have taken. (-1 to finish)" << endl;

    cin >> score;  // todo: check correctness - a number, 0 <= score <= 100, etc.
    if (score == -1) 
       break;
    cnt++;
    scores += score;
}

double test_avg = 0.0;
if (cnt > 0)
    test_avg = double(scores) / cnt;