Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

math operation doesn't return expected result

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading