对我是否需要一个哨兵值来终止我的 do while 循环以允许多个条目感到困惑

Confused on wether i need a sentinal value to terminate my do while loop to allow for more than one entry

本文关键字:循环 while do 许多个 我的 终止 是否 哨兵 一个      更新时间:2023-10-16

我将使用do while循环来打印出平均成绩和字母等级,但随后我被要求使用另一个循环来确定多个等级。

我的

问题是我的 do while 循环得到了一个无限循环,我不确定何时需要终止它。

#include <iostream>
using namespace std;
int main()
{
    float avgscore;
    int count;
    cout << "Please enter enter your average score inpercent format. I.E. 95.6%" << endl;
    cin >> avgscore;
    do
    {
        if (avgscore >= 90)
        cout << "Your exam score is: " << avgscore << " Which results in the grade an A!"<<endl;
        else if (avgscore >= 80)
            cout << "Your exam score is: " << avgscore << " Which results in the grade of a B!" << endl;
        else if (avgscore >= 70)
            cout << "Your exam score is: " << avgscore << " Which results in the grade of a C!" << endl;
        else if (avgscore >= 60)
            cout << "Your exam score is: " << avgscore << " Which results in the grade of a D!" << endl;
        else if (avgscore <= 59.9)
            cout << "Your exam score is: " << avgscore << " Which results in the grade of a F!" << endl;
    }
    while (avgscore > 0); //This is my problem here, but i'm not sure what i need here to end it.
    // I need to add another loop here to allow for more than one entry.
    return 0;
}

任何帮助将不胜感激!

您可以简单地放置以下行

cout << "Please enter enter your average score inpercent format. I.E. 95.6%" << endl;
cin >> avgscore;

do-while内部,以便能够通过输入<=0的值来对循环进行皮肤化。

这里的关键思想是你需要有能力在循环中更改avgscore的值,以便检查条件会因为false,如果你愿意的话。

你这里有一个逻辑问题。 您的用户在进入循环之前输入avgscore,然后您尝试循环,在那里它没有机会更改。

您需要重新构建它,以便您的用户可以输入其输入,然后它可以基于该输入进行循环。

伪代码:

do {
    //ask for input
    cout << "Please enter enter your average score inpercent format. I.E. 95.6%" << endl;
    cin >> avgscore;
    //Print stuff based on input
    //ask if they want to do another 
    cout <<"want to do another? Enter 'n' to exit"<<endl;
    cin >> continue;
} while ( continue != "n");
cout<<"exiting..."<<endl;
//Note:  Syntax on all this is way off as I haven't been writing c++ lately.

看起来您需要移动do来包围输入。

float avgscore = 0.0; //always initialize
int count = 0; //always initialize
do
{
    std::cout << "Please enter enter your average score in percent format. I.E. 95.6%"
        << " (enter 0 to end)" << std::endl;
    std::cin >> avgscore;
    //if statements
} while (avgscore > 0);

这将循环直到用户输入 0,但在此之前的每次它都会输出分数和字母等级。