2016-12-30 50 views
-2

有這個簡單的代碼問題嗎?問題是,無論何時按B或C,總是隻添加其他功能。帶「else if」方法問題的基本計算器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; 
     } 
+3

'='是賦值運算符,使用'=='比較。 'if(choice =='A')',等等...... – Unimportant

+1

格式化是一個悲劇。 –

回答

1

的問題是,在你的if語句使用的是 '=',它應該是 '=='

例如:

if (choice = 'A') 

應該是

if (choice == 'A') 
+0

謝謝你,現在工作:) –

2
if (choice = 'A') 

=是賦值運算符,其中分配給'A'choice

這可能不是你想要的。您可能想要比較choice'A'。平等比較使用==操作:

if (choice == 'A')