为什么不做我的做法而工作

时间:2013-03-02 10:02:17

标签: c++ while-loop

你能帮我解决一下这个程序吗?它不会cout z。

int main()
{
    using namespace std;
    int x, y, z, a;
    cout << "Please enter a number" << endl;
    cin >> x;
    cout << "Please enter another number" << endl;
    cin >> y;
    cout << "What do you want to do with these numbers?" << endl;
    cout << "1 = +" << endl;
    cout << "2 = -" << endl;
    cout << "3 = *" << endl;
    cout << "4 = /" << endl;
    cin >> a;

    do {
        z = add(x, y);
    } while (a == 1);

    do {
        z = sub(x, y);
    } while (a == 2);

    do {
        z = mul(x, y);
    } while (a == 3);

    do {
        z = dis(x, y);
    } while (a == 4);

    cout << z;
    return 0;
}

我尝试使用do while语句,但我无法让它工作。 - -编辑 - - 添加了适当的缩进,为什么它不会这样做?

3 个答案:

答案 0 :(得分:2)

无论您输入哪个选项,它都会进入该do-while循环并且永远不会退出,因为条件将始终得到满足。防爆。如果我输入1,那么它将进入:

do {
    z = add(x, y);
} while (a == 1);

因为a总是1,所以永远不会退出。其他条件也是如此。相反,您可以使用switch语句。类似的东西:

switch(a) {
    case 1 : z = add(x, y);
             break;
    case 2 : z = sub(x, y);
             break;
    case 3 : z = mul(x, y);
             break;
    case 4 : z = div(x, y);
             break;
    default : cout<<"Please choose a valid option to proceed.";
}
cout << z;
return 0;

此外,在这种情况下,您不使用do-while。即使你退出循环,它也总是除(x,y),因为do-while是这样的,它进入然后随后检查条件。但是你可以使用这样的while循环:

while(a==1) {
    z = add(x, y);
    a = -1;
}

while(a==2) {
    z = sub(x, y);
    a = -1;
}

while(a==3) {
    z = mul(x, y);
    a = -1;
}

while(a==4) {
    z = div(x, y);
    a = -1;
}

答案 1 :(得分:0)

声明:

 while( 1 >= a <= 4)

不正确[嗯,这是正确的C语法,但它很可能不是你想要的,因为它确实如此]:

while( (1 >= a) <= 4);

由于(1 >= a)的结果为01,因此始终为<= 4。你需要这样做:

while ( (1 >= a) && (a <= 4) );  

[括号仅为清晰起见,您可以删除两个内部括号组]

答案 2 :(得分:-1)

您的代码正在进入无限循环,如此修改

   int main()
{
using namespace std;
int x, y, z, a;
do
{
cout << "Please enter a number" << endl;
cin >> x;
cout << "Please enter another number" << endl;
cin >> y;
cout << "What do you want to do with these numbers?" << endl;
cout << "1 = +" << endl;
cout << "2 = -" << endl;
cout << "3 = *" << endl;
cout << "4 = /" << endl;
cin >> a;
switch(a)
{
  case 1:
    z = add(x, y);
    break;
  case 2:
    z = sub(x, y);
    break;
  case 3:
    z = mul(x, y);
    break;
  case 4:
    z = dis(x, y);
    break;
}  
cout << z;
} while( 1 >= a <= 4)
return 0;
}

根据lokoko的建议修改