0

你能修复这个程序吗?它不会计算 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 语句,但我无法让它工作。---编辑---添加了适当的缩进,为什么它不能自动这样做?

4

3 回答 3

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;
}
于 2013-03-02T10:07:02.290 回答
0

该声明:

 while( 1 >= a <= 4)

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

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

并且由于 的​​结果(1 >= a)是 要么01所以它总是<= 4。你需要做:

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

[括号只是为了清楚起见,可以去掉里面的两组括号]

于 2013-03-02T10:26:42.777 回答
-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的建议修改

于 2013-03-02T10:06:27.520 回答