I have something like this in my code:
a = -2;
b = 1/a;
printf("%d", b);
The printf is printing 0. Does anyone know why this is? And what do I do to get -0.5? I also tried "%.2f"
and that gave me 0.00.
Thanks
I have something like this in my code:
a = -2;
b = 1/a;
printf("%d", b);
The printf is printing 0. Does anyone know why this is? And what do I do to get -0.5? I also tried "%.2f"
and that gave me 0.00.
Thanks
You've run into integer arithmetic. In C and many other languages, divisions like 1/2
give you a result you're not expecting because both 1
and 2
are integers, and the result is also an integer. Integers can't store 0.5
, so the result gets its fractional part truncated, and you end up with 0.
To perform fractional arithmetic, you need to use float
s, double
s, etc. You can either type that directly as 1.0 / -2.0
, or you can cast your values to other types with (double) a / b
. As long as at least one of the operands handles fractional parts, your result will also contain fractions.
Since, data types for a and b are not specified i am assuming them to be of type int.
In C, the result of an operation depends on the data types of the operands. The result can not have more precision/accuracy/size than the operands themselves. What you are facing is related to integer arithmetic rules.
Now, in your case: both -2 and 1 in b = 1/a
are integers so the result will be truncated to an integer, so -1/2 = -0.5 truncated to 0. %.2f
will not help as the value in b is already 0.
So to cause b to be -0.5. You need to have both a and b as float and print using %f.
or,
You can have a as int and b as float and write b as 1.0/a
. (Here 1 is float a is int so the result will be float typecasting a to int).
or,
via typecasting: b = 1 / (float)a;
You need to go through typecasting rules.