带有“else if”方法的基本计算器发布c ++

时间:2016-12-30 22:41:42

标签: c++

有这个简单的代码问题吗?问题是每当我按下B或C时,总是只添加其他功能。

PS:这是代码

#include <iostream>

 using namespace std;

  int main()
  {
    char choice;
    int number1, number2;
    int ans1, ans2, ans3, ans4;
    cout << "Insert first number. \n";
    cin >> number1;
    cout << "Insert second number. \n";
    cin >> number2;
    cout << "Choice just one. A is for addition, B for subtraction , C for      multiplication, D for division \n";
    cin >> choice;
    if (choice = 'A' )
    {ans1 = number1 + number2;
    cout << " answer is " << ans1 << endl;
     }
    else if (choice = 'B' )
    {ans2 = number1 - number2;
    cout << "Answer is" << ans2 << endl;
     }
     else if (choice = 'C')
     {ans3 = number1 * number2;
     cout << "answer is " << ans3 << endl;
     }
     else if
     (choice = 'D')
      {ans4 = number1 / number2;
      cout << "answer is" << ans4 << endl;
     }
    else
     cout << "Problem \n";




   return 0;
      }

2 个答案:

答案 0 :(得分:2)

if (choice = 'A' )

=是赋值运算符,它将'A'分配给choice

这可能不是你想要的。您可能希望将choice'A'进行比较。平等比较使用==运算符:

if (choice == 'A')

答案 1 :(得分:1)

问题是你的if语句中你使用'=',它应该是'=='

例如:

if (choice = 'A')

应该是

if (choice == 'A')