calculator error

Hey guys I'm still a beginner in c++ and i wanted to make a calculator in c++,
the problem is that when using my calculator the first answer is always wrong, its always (4309918) actually and any equation entered after that has the answer of the previous one. i don't know why.

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 <iostream>

using namespace std;

int main()
{
    while(1==1){
    int a;
    int b;
    int sum;
    int type;
    cout<< "Welcome to the calculator! \n";
    cout<< "Which type of operand do you want to use? \n 1-Addition \n 2-Subtraction \n 3-Multiplication \n 4-Division \n";
    switch(type){
        case 1:
            sum=a+b;
            break;
        case 2:
            sum=a-b;
            break;
        case 3:
            sum=a*b;
            break;
        case 4:
            sum=a/b;

    }


    cin>> type;
    cout<< "Please enter a number \n";
    cin>> a;
    cout<< "Select another one \n";
    cin>> b;
    cout<<"The answer is:"<< sum << endl;




}

    return 0;


}
You have things taking place in the wrong sequence. You need to get the input via cin before you can process it in the switch-case statement.

Only line 35
 
    cout << "The answer is: " << sum << endl;
should be after the switch-case block.

The others (lines 30 to 34) should be moved just above line 14 (the switch statement).

Note the answer 4309918 is garbage content since none of the variables are initialised. It is good practice to give an initial value to avoid unpredictable results:
1
2
3
4
        int a = 0;
        int b = 0;
        int sum = 0;
        int type = 0;
Thank you so much!
Topic archived. No new replies allowed.