执行while循环通知



在我的大学里,我们还没有涉及到do while循环,所以我想在我们做之前尝试一个,但是我遇到了一个问题,我想让程序根据用户的输入执行不同的函数,A执行加法,B执行减法,C退出程序。
我用do写的程序,不管用户输入什么,都一个接一个地执行这些函数,我不确定如何使其正常工作。

任何建议都非常感谢。

有几点需要注意。您让用户为选择输入一个字符,因此将userChoice设置为一个字符。注意,在本例中,do-while是如何用于输入验证的。我将额外的while循环以分号结尾更改为条件语句。你可以用开关"菜单驱动程序"代替if和else if。这是你想要的工作程序。如果你想在整个条件语句周围使用do-while而不是将其用作输入验证,那么在所有条件语句周围使用do-while并在它不是c时进行检查。

#include <iostream>
#include <string>
using namespace std;
int main()
{
  char userChoice;
  int vaulue1;
  int vaulue2;
  int addtionValue;
  int subtractionValue;
  cout << "Choice A: will preform an addition" << endl;
  cout << "Choice B: will preform a subtraction" << endl;
  cout << "Choice C: will quitn" << endl;

    do
      {
        cout << "Enter your choicen" << endl;
        cin >> userChoice;
      } while(userChoice != 'A' && userChoice != 'B' && userChoice != 'C');
    if(userChoice == 'A')
      {
        cout << "Additionn" << endl;
        cout << "Please enter the first value you want to addn" << endl;
        cin >> vaulue1;
        cout << "Please enter the second value you want to addn" << endl;
        cin >> vaulue2;
        addtionValue = vaulue1 + vaulue2;
        cout << "The addtion answer is " << addtionValue << endl;
      }
    else if(userChoice == 'B')
      {
        cout << "Subtractionn" << endl;
        cout << "Please enter the first value you want to subtractn" << endl;
        cin >> vaulue1;
        cout << "Please enter the second value you want to subtractn" << endl;
        cin >> vaulue2;
        subtractionValue = vaulue1 - vaulue2;
        cout << "The subtract answer is " << subtractionValue << endl;
      }
    else if(userChoice == 'C')
      {
        cout << "Exit ";
        return -1;
      }
    return 0;
}
  1. 你应该只使用一个"while" -只是第一个while是正确的
  2. 其他"while"为空循环;清洗
  3. 最好使用"switch - case"

当您输入A作为输入时,您的方法想要给A另一个

最新更新