1

I'm using a function, but the code will not work. I broke the function down into its parts and tried to understand what's going on myself. I got this:

int res;
res = (1 / 2) * 2 + 2;
printf("%d", res);

Calculating myself:

(1 /2) = 0.5

0.5 * 2 = 1

1 + 2 = 3

(1 / 2) * 2 + 2 = 3, right?

However, when I run the code it gives me an output of '2', instead of '3'.

When I try this: (making '(1 / 2)' to '0.5')

int res;
res = 0.5 * 2 + 2;
printf("%d", res);

I get an expected output of '3', which is weird because the example above is theoretically the same as the lower one. Does it have to do with my compiler not knowing simple math prioritising rules?

user438383
  • 5,716
  • 8
  • 28
  • 43
dedpunkrz
  • 69
  • 4
  • 2
    `1 / 2` returns an integer result, which would be equal to `1 >> 1`, which would be `0`. – jxh Dec 20 '21 at 22:31
  • 2
    If you want the division to return a floating point result, you would need to make one or both of its arguments have a floating point type. So, `1. / 2` or `1 / 2.` or `1. / 2.` – jxh Dec 20 '21 at 22:33
  • Does this answer your question? [What is the behavior of integer division?](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) – 1201ProgramAlarm Dec 20 '21 at 23:10

1 Answers1

5

1/2 actually tries to return an integer result (0), which multiplied by 2 is also 0.

You can try typecasting it

float res;
res = (float)1/(float)2 * 2 + 2;
printf("%f", res);

It will force the result to be a float result (0.5), which will lead to the correct answer

Alexander Santos
  • 1,458
  • 11
  • 22