Else if else statement calculator

Nov 29, 2011 at 2:38pm
Hi, I built a basic calculator that could use addition (or subtraction, etc, if I changed the code) but I wanted to build one that did addition, subtraction, multiplication and division depending on what the user wanted.

I've encountered a problem using the Else If Else statement. It seems not to read it and simply goes straight to ending the program. I've switched it around so many times and tried everything I can think of, but I'm obviously not getting it! Can somebody help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int num1;
    cout << "Enter a number: ";
    cin >> num1;

    char op;
    cout << "Enter an operator \n 1 for addition, 2 for subtraction, 3 for multiplication or 4 for division: ";
    cin >> op;

    int num2;
    cout << "Enter second number: ";
    cin >> num2;

    int answer, answer1, answer2, answer3;
    if (op == 1){
        answer = num1 + num2;
        cout << "Answer: " << answer << endl;;
    } else {
        if (op == 2){
            answer1 = num1 - num2;
            cout << "Answer: " << answer1 << endl;
        } else {
            if (op == 3){
                answer2 = num1 * num2;
                cout <<  "Answer: " << answer2 << endl;
            } else {
                if (op == 4){
                    answer3 = num1 / num2;
                    cout << "Answer: " << answer3 << endl;
                }

                }}}




    system("PAUSE");
    return 0;
}
Nov 29, 2011 at 2:51pm
op is a char so you are reading a single character into it. 1 is not the same as '1'. If you want op to be a char you can make the comparison like this op == '1'
Or you can change op to be an int and the it should work.
Nov 29, 2011 at 2:52pm
'op' is a char. When the user inputs 1 (the number), the program reads '1' (the character). The value of '1' is not 1 (it's 49 or something).

You can fix it either by changing the type of 'op' to int, or by replacing your conditionals to:
if (op == '1') { ... }

The first option is easier; the second option is more generic (i.e. you can replace 1/2/3/4 with A/S/M/D or +/-/*// (okay bad choice of separator there, whatever)).

[edit] line 24 also has a double ';' at the end. Bad (but probably meaningless)!
Last edited on Nov 29, 2011 at 2:53pm
Nov 29, 2011 at 4:01pm
Thanks guys! I'd switched it around so much I forgot all about setting op to char ^_^
Topic archived. No new replies allowed.