c++ - 我应该在这里使用 goto 语句吗?

标签 c++ goto

一位好先生告诉我 goto 语句不好,但我不明白我怎么不能在这里使用它:

int main()
{   
   using namespace std;
   int x;
   int y;
   int z;
   int a;
   int b;
   Calc: //How can i get back here, without using goto?
   {
   cout << "To begin, type a number" << endl;
   cin >> x;
   cout << "Excellent!" << endl;
   cout << "Now you need to type the second number" << endl;
   cin >> y;
   cout << "Excellent!" << endl;
   cout << "Now, what do you want to do with these numbers?" << endl;
   cout << "Alt. 1 +" << endl;
   cout << "Alt. 2 -" << endl;
   cout << "Alt. 3 *" << endl;
   cout << "Alt. 4 /" << endl;
   cin >> a;

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

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

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

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

cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;

    if (b == 1) {
    goto Calc;
}
cout << "Happy trails!" << endl;
return 0;
}

如您所见,它是一个计算器。另外,如果您愿意,能否建议一种更好的方法(如果存在)让用户选择操作(+ - */)。头文件受到控制。 对于很多 cout 语句,我深表歉意。

最佳答案

这是一个使用 do/while 循环结构的清理和格式正确的版本:

using namespace std;

int main()
{   
    int x, y, z, a, b;

    do {
        cout << "To begin, type a number" << endl;
        cin >> x;
        cout << "Excellent!" << endl;
        cout << "Now you need to type the second number" << endl;
        cin >> y;
        cout << "Excellent!" << endl;
        cout << "Now, what do you want to do with these numbers?" << endl;
        cout << "Alt. 1 +" << endl;
        cout << "Alt. 2 -" << endl;
        cout << "Alt. 3 *" << endl;
        cout << "Alt. 4 /" << endl;
        cin >> a;
        if (a == 1) {
            z = add(x, y);
        }
        else if (a == 2) {
            z = sub(x, y);
        }
        else if (a == 3) {
            z = mul(x, y);
        }
        else if (a == 4) {
            z = dis(x, y);
        }
        cout << "The answer to your math question is ";
        cout << z << endl;
        cout << "Do you want to enter another question?" << endl;
        cout << "Type 1 for yes" << endl;
        cout << "Type 0 for no" << endl;
        cin >> b;
    } while (b != 0);
    cout << "Happy trails!" << endl;
    return 0;
}

关于c++ - 我应该在这里使用 goto 语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161018/

相关文章:

c++ - FreeRTOS CPP 函数指针

c++ - 使用多个元素计算排列

c++ - 单例线程安全类

c - goto 语句的行为

language-agnostic - 继续认为有害吗?

c++ - goto 和析构函数兼容吗?

c++ - snprintf 是否可能返回以 '\0' 开头的字符数组?

javascript - 如何为字符串生成唯一但一致的 N 位哈希(小于 64 位)?

c++ - goto 和 junping 循环循环 c++

c++ - 使用 "for"打破 "break"循环被认为是有害的?