Stuck need advice please

Hello there, I'm new to C++ and I was trying to do kind of a calculator, with simple operations like subtracting two numbers. I read most of the guide, but I can't seem to find out, why the result shows "X". This is the code I made:

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

using namespace std;

int main ()
{
    int a, b;
    float f;
    char operation;

    cout << "Select operation (0- addition, 1- subtraction, 2- multiplication, 3- division)";
    cin >> f;

    if (f = 0)
    {
    operation = a+b;
    }
    else if (f = 1)
    {
    operation = a-b;
    }
    else if (f = 2)
    {
    operation = a*b;
    }
    else if (f = 3)
    {
    operation = a/b;
    }
    else
    {
    cout << "Error:Operation unknown!" << endl;
    }

    cout << "Enter first number:";
    cin >> a;
    cout << "Enter second number:";
    cin >> b;

    cout << "You have entered numbers:" << a << " and " << b << endl;
    cout << "Operation result:" << operation << endl;

    return 0;

}


Btw, first I used operation as int, but I changed it to char as I thought it would be better (but neither way works).
f = 0 assign 0 to f, for the comparison use ==
Also, f needs to be an integral type, not a float.

Further, you are performing the operation on lines 16/20/24/28 on a and b
before you've asked the user for their values.
Thanks I've done what you suggested, but I still can't see the result of the operation (now for some reason I get a smiley...not joking).Is it the compiler maybe? I use Code Blocks.
operation shouldn't be a char. Make it an int.
Thank you! It finally works.
I have played a bit with the program (using several numbers) and I found out that the dividing part had a problem. If I tried to divide 3 by 2 it results 1, instead of 1.5 (and 5/2 = 2). I tried making operation a double and a long to see if it works but it doesn't.
if you divide two integers, the result will be an integer, even if you assign it to a double.

ie:
1
2
3
int a = 3, b = 2;

c = a / b;  // a/b will be an integer (1), even if c is a double 


Therefore if you want floating point division, you have to divide floating points:

1
2
3
double a = 3, b = 2;

c = a / b;  // now a/b is a double (1.5) 
@Disch,
What if OP wants to store a and b in integers?

I would say it would be best to do a typecast here:
c = (double)a / (double)b;

that way, the result will still be a double precision float; but the operands can be integral.
Thank you Disch and chrisname. It works now.
Topic archived. No new replies allowed.