我如何结束while循环?

时间:2016-09-04 21:53:14

标签: c++

尝试循环,直到用户输入0.0以终止循环。但是我得到一个错误。用户应该输入gpa并得分,直到他完成终止。有什么帮助吗?

#include <iostream>

using namespace std;

int main() {
    double gpa; // gets the double entered by the user
    int score; // gets to store the score
    bool done = false;

    // statements to print to the user

    while (!done) {
        cout << "Please enter your GPA(enter 0.0 to end): ";
        cin >> gpa;
        cout << "Please enter your entrance score: ";
        cin >> score;

        // the if statements
        if (gpa >= 3.7 && score >= 32) {
            cout << "Congratulations!. You are hereby admitted to ABC Medical University";
        }
        else if (gpa < 3.7) {
        cout << "you are denied";
        }
        else if (gpa == 0.0)
            done = true;
    }// end while loop
    return  0;
}

5 个答案:

答案 0 :(得分:1)

else if (gpa < 3.7)符合条件,因此下一个else if不会处理。

或许将行更改为else if (gpa < 3.7 && gpa > 0.0)

答案 1 :(得分:0)

else if (gpa < 3.7) {
    cout << "you are denied";
}
else if (gpa == 0.0)
     done = true;

0.0然后是3.7。所以重新安排你的if:

else if (gpa == 0.0)
     done = true;
else if (gpa < 3.7) {
    cout << "you are denied";
}

会解决它。

答案 2 :(得分:0)

您可以使用break语句退出循环。

答案 3 :(得分:0)

否则
if(gpa == 0.0)break;

答案 4 :(得分:0)

else if (gpa < 3.7) // this condition hides condition below because any value smaller than 3.7 even 0.0 will succeed this condition so any else block will be skipped
{
    cout << "you are denied";
}
else if (gpa == 0.0) // this condition will never be executed because 0.0 is smaller than 3.7 which it is covered by the above condition.
           done = true;

正确的表单作为您的代码:

交换条件:

else if (gpa == 0.0)
         done = true;
else if (gpa < 3.7) 
{
    cout << "you are denied";
}

我认为通过放置第一个条件来优先考虑这个循环退出条件:

while (1) 
{
    cout << "Please enter your GPA(enter 0.0 to end): ";
    cin >> gpa;

    else if (gpa == 0.0) // high priority so if the user enters 0.0 no need to continue
        done = true;

    if(done)
        break; // exiting quickly and rightously

    cout << "Please enter your entrance score: ";
    cin >> score;

    // the if statements
    if (gpa >= 3.7 && score >= 32) {
        cout << "Congratulations!. You are hereby admitted to ABC Medical University";
    }
    else if (gpa < 3.7)
    {
            cout << "you are denied";
    }

}// end while loop