Home > database >  math operation doesn't return expected result
math operation doesn't return expected result

Time:12-21

So, 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?

Thanks in advance.

CodePudding user response:

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

  • Related