mardi 2 février 2016

C++ calling different methods if char is entered

Hello I'm trying to create a console application that allows the user to input a single character to preform an arithmetic operation.

Currently the program only adds the two numbers together even if I input an m, meaning multiply. I believe it is going straight into the first if statement for some reason even if I dont want addition.

 #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;
    }

Aucun commentaire:

Enregistrer un commentaire