2016-02-03 21 views
0

你好我試圖創建一個控制檯應用程序,允許用戶輸入單個字符進行算術運算。C++調用不同的方法,如果字符輸入

目前,程序只會將兩個數字相加,即使我輸入m,意味着乘。我相信,即使我不想加入,它也會因爲某種原因直接進入第一條if語句。

#include <iostream> 
using namespace std; 

int add(int a, int b) 
{ 
    int c; 
    c = a + b; 
    return c; 
} 
int subtract(int a, int b) 
{ 
    int c; 
    c = a - b; 
    return c; 
} 
int multiply(int a, int b) 
{ 
    int c; 
    c = a * b; 
    return c; 
} 
int divide(int a, int b) 
{ 
    int c; 
    c = a/b; 
    return c; 
} 
int remainder(int a, int b) 
{ 
    int c; 
    c = a % b; 
    return c; 
} 

int main() 
{ 
    int a; 
    int b; 
    char op; 

    cout << "****************Integer Calculator**************** " << endl << "Press enter to continue." << endl; 


    cout << "Enter the first integer: " << endl; 
    cin >> a; 
    cout << "Enter the second integer: " << endl; 
    cin >> b; 

    cout << "What operation would you like to perform? Enter a single character " << endl << "Add - A , a or + " << endl << 
     "Subtract - S , s or - " << endl << "Multiply - M , m or * " << endl << "Divide - D , d or/" << endl << "Remainder - R , r or % " << endl; 
    cin >> op; 

    if (op ='A' || 'a' || '+') 
    { 
     int answer1 = 0; 
     answer1 = add(a, b); 
     cout << "The answer is: " << answer1 << endl; 
     system("PAUSE"); 
     return 0; 
    } 
    else if(op == 'S' || 's' || '-') 

    { 
     int answer2 = 0; 
     answer2 = subtract(a, b); 
     cout << "The answer is: " << answer2 << endl; 
     system("PAUSE"); 
     return 0; 
    } 
    else if (op == 'M' || 'm' || '*') 
    { 
     int answer3 = 0; 
     answer3 = multiply(a, b); 
     cout << "The answer is: " << answer3 << endl; 
     system("PAUSE"); 
     return 0; 
    } 
    else if (op == 'D' || 'd' || '/') 
    { 
     int answer4 = 0; 
     answer4 = divide(a, b); 
     cout << "The answer is: " << answer4 << endl; 
     system("PAUSE"); 
     return 0; 

    } 
    else if (op == 'R' || 'r' || '%') 
    { 
     int answer5 = 0; 
     answer5 = remainder(a, b); 
     cout << "The answer is: " << answer5 << endl; 
     system("PAUSE"); 
     return 0; 
    } 

回答

2

您的邏輯錯誤,您正在使用賦值運算符來啓動。

if (op ='A' || 'a' || '+') 

應該是:

if (op == 'A' || op == 'a' || op == '+') 

通常像這樣的東西,我們使用switch

switch(toupper(op)) 
{ 
    case 'A': 
    case '+': 
     // Do adding... 
     break; 

    case 'S': 
    case '-': 
     // Do subtraction... 
     break; 

    // etc... 

    default: 
     cout << "Unknown operation : " << op << endl; 
} 
0

在你的if語句

(op ='A' || 'a' || '+') 

如果op等於'A',則不測試。你設置op等於'A',然後測試'a'和'+'是否爲真,它們是。要解決這個問題,請使用==操作符,並對每種情況進行如下測試:

if (op == 'A' || op == 'a' || op == '+')... 
else if(op == 'S' || op == 's' || op == '-')... 

// and so on