嵌套的do-while循环和while循环

时间:2015-09-15 03:37:22

标签: visual-c++

在此程序中,0到4以外的选项都是无效的,因此会一次又一次地要求用户选择他/她的选择。然后,作为选择" 1"输入后,程序将执行两个数字的添加。因此,它将继续询问两个数字(x和y)然后打印出计算结果。然后用户可以选择执行另一个计算。只要用户没有选择" 5"要退出程序,程序将继续执行用户选择的不同计算。我想在选择== 5时退出程序。但它只会让我回复#34;您的选择无效,请再次输入。"这是代码:

#include <iostream>
using namespace std;

int main()
{
int choice, x, y, z;

do
{
    cout << "Math is easy!" << endl << "1. Perform addition" << endl << "2. Perform subtraction" << endl <<
        "3. Perform multiplication" << endl << "4. Perform division" << endl << "5. Quit" << endl << "Please enter your choice[1 - 5]:" << endl;
    cin >> choice;
    while (choice < 1 || choice > 4)
    {
        cerr << "Your choice is invalid, please enter again.";
        cin >> choice;
    }
    cout << "Please enter x:" << endl;
    cin >> x;
    cout << "Please enter y:" << endl;
    cin >> y;
    if (choice == 1)
    {
        z = x + y;
        cout << x << "+" << y << "=" << z << endl;
    }
    if (choice == 2)
    {
        z = x - y;
        cout << x << "-" << y << "=" << z << endl;
    }
    if (choice == 3)
    {
        z = x * y;
        cout << x << "*" << y << "=" << z << endl;
    }
    if (choice == 4)
    {
        z = x / y;
        cout << x << "+" << y << "=" << z << endl;
    }



} while (choice != 5);
system("pause");
return 0;

}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

在while循环之前,您可以查看if(choice == 5)break;

if(choice == 5)// if choice == 5 break loop. or exit(0);
    break;
while (choice < 1 || choice > 4)
{
    cerr << "Your choice is invalid, please enter again.";
    cin >> choice;
}
.
.
.
.
if (choice == 1)
{
    z = x + y;
    cout << x << "+" << y << "=" << z << endl;
}
else if (choice == 2)
{
   //code
}
else if (choice == 3)
{
   //code
}

使用if - elseif而不是使用多个if条件。您也可以使用switch