logic explanation requested.

can someone please explain how "x" is equal to "2"

1
2
3
4
5
6
7
8
9
10
11
12
int a, b;
a=2;
b=3;
float x;
int main()
{

    x = (float)((a+b)/2);
    std:cout << x;


}


thank you, i am a begginer.
What do you expect "x" to equal? Remember there are no fractions when using integer math.

First of all this won't compile.

Second a, b are integers so the computation is on integers meaning the "/" is equal to div here. if you change a, b to float then you will get output in float (after you fix the compilation errors)
order of operations destroyed your casting efforts.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
    int a = 2;
    int b = 3;
    float x;

    x = (float(a + b) / 2);
    std::cout << x;
}


thank you.
Topic archived. No new replies allowed.