为什么这个应该请求操作然后进行必要计算的代码不起作用

Why is this code which is supposed to request an operation then do the necessary calculations not working

include using namespace std;

int main() {
  float n1, n2, sum, diff, pro, quot;
  char f;

  cout << "PLease enter your function(A,S,D,M or X to end the program" << endl;
  cin >> f;

  while (f != 'A', 'S', 'D', 'M', 'X') {
    cout << "Invalid Operation" << endl;
    cout << "PLease enter your function(A,S,D,M or X to end the program"
         << endl;
    cin >> f;
  }

  if (f == 'X') return 0;
  if (f == 'A', 'S', 'D', 'M') {
    cout << "Please enter two numbers";
    cin >> n1 >> n2;

    if (f == 'A') {
      sum = n1 + n2;
      cout << sum;
    }

    else if (f == 'S') {
      if (n1 > n2) {
        diff = n1 - n2;
        cout << diff;
      } else {
        diff = n2 - n1;
        cout << diff;
      }
    } else if (f == 'D') {
      if (n1 > n2) {
        quot = n1 / n2;
        cout << quot;
      } else {
        quot = n2 / n1;
        cout << quot;
      }
    } else if (f == 'M') {
      pro = n1 * n2;
      cout << pro;
    }
  }

  return 0;
}

它不接受 A,S,M,D

您的 while 语句有问题。它使用的是逗号表达式,这不是您想要的,因为它最终评估为 'X'。您需要分别比较 f 和您的每个选项。

完成此操作的一种方法是将 while 语句中的比较扩展为类似

的内容
while (f != 'A' && f != 'S' && f != 'D' && f != 'M' && f != 'X')
{
  ...
}

下面几行的 if 语句也是如此。

您的代码的问题是逻辑不在 while 循环内,这就是为什么它无法通过必要的 if 和 else,所以我编辑了您的代码并应用了一些更改。

变化:

-->我删除了代码的第一个 cout,因为您只需要 while 循环中的那个 "Input statement"。

-->我把条件语句放在了你的 while 循环中。

-->我添加了一个新的else语句来放置单词"Invalid Operation"

using namespace std;

int main()
{
    float n1,n2,sum,diff,pro,quot; char f;

    while (f!='A','S','D','M','X'){
        cout<<"Please enter your function(A,S,D,M or X to end the program"<<endl;
        cin>>f;

        if(f=='X'){
           return 0; 
        }
        else if (f=='A'){
            cout<<"Add";
            sum=n1+n2; 
            cout<<sum<<endl;
        }
        else if (f=='S'){
            cout<<"Subtract";
            if (n1>n2){
                diff=n1-n2;
                cout<<diff<<endl;
            }
            else{
                diff=n2-n1;
                cout<<diff<<endl;
            }
        }
        else if (f=='M'){
            cout<<"Multiply";
            pro=n1*n2; 
            cout<<pro<<endl;
        }
        else if (f=='D'){
            cout<<"Divide";
            if (n1>n2){
                quot=n1/n2;
                cout<<quot<<endl;
            }
            else{
                quot=n2/n1;
                cout<<quot<<endl;
            }

        }
        else{
            cout<<"Invalid Operation"<<endl;
        }
    }

    return 0;
}