What is wrong with my code? [SOLVED]

Hello , I'm new to C++, I've been trying to code a calculator, but when I run my code, it says something is wrong with it, I rechecked the code 4 times but still couldn't find what's wrong with it, can someone please tell me so I can correct it, thanks!

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
  #include <iostream>
#include <cmath>
using namespace std;

int main()
{

    double num1,num2;
    char = op;
    cout << "Enter the first number: ";
    cin >> num1;
    cout << "( + - * / #)" << endl;
    cout << "Enter operator: ";
    cin >> op;
    cout << "Enter the second number: ";
    cin >> num2;

    double result;

    if(op == '+'){
        result = num1 + num2;
    } else if(op == '-'){
        result = num1 - num2;
    } else if(op == '*'){
        result = num1 * num2;
    } else if(op == '/'){
        result = num1 / num2;
    } else if(op == '#'){
        result = pow(num1, num2);
    } else {
        cout << "~Invalid Operator~" << endl;
    }

    cout << "Successfully executed: " << result << endl;





    return 0;
}
Last edited on
 In function 'int main()':
Line 9: error: expected unqualified-id before '=' token


Have a closer look at this line.
Oh my, I feel embarrassed right now, thanks dude!
Hi,

Don't worry about it. I once spent 3 hours working out why my code wouldn't compile. Turns out I was missing a semi colon.
Hello Surhurt,

You may want to consider changing line 26 to } else if(op == '/' && num2 !=0){. Otherwise you could get a run time divide by (0) zero error.

Also a few blank lines makes it easier to read.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    double num1,num2;
    char = op;

    cout << "Enter the first number: ";
    cin >> num1;

    cout << "( + - * / #)" << endl;
    cout << "Enter operator: ";
    cin >> op;

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

The first goal should be to make your code easier to read. First for your-self and then for others.

To make a point and not to say that what you did is wrong, but this is easier to read and follow. In the end use what you are use to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (op == '+')
{
    result = num1 + num2;
}
else if (op == '-')
{
    result = num1 - num2;
}
else if (op == '*')
{
    result = num1 * num2;
}
else if (op == '/')
{
    result = num1 / num2;
}
else if (op == '#')
{
    result = pow(num1, num2);
}
else
{
    cout << "~Invalid Operator~" << endl;
}


Andy
Thanks Andy!, I will keep that in mind next time I want to code.
Dang 3 hrs for a missing semicolon. Thats a hard lesson learned.
Topic archived. No new replies allowed.