Can Anyone help me why x2 prints zero. I guess because of floating point representation X1 is rounded off, is there way to keep the precession.
long double x1, x2;
x1= 0.087912088; // Note: 360/4095 = 0.087912088
x2 = 360/4095;
printf("%Lf, %Lf \n",x1, x2);
Result:
x1 =0.087912
x2= 0.000000
Built-in operators work on objects of the same type. The result is the same type as the parameters. In this case the division is done on two integers and thus the result is an integer.
Thus I would expect a result of 0.
If the operators on a built-in type are different the one will promoted so that they have the same type (and the result is also that type). So what you want is:
The problem is integer truncation .. you are dividing two integers => the result will be another integer with the fractional part thrown away. (So for instance in the case when the real result of an integer division would be 3.9, truncation would make it 3 (ie. it doesn't round)).
In your case, if you change this to:
you'll get
as output.
I.e., as soon as one or both of the operands of the division operator
/
are float/doubles, the result will be too (i.e., it will be "promoted" to float/double). So I could have changedx2
toor
and would have gotten the same result as above.
As mentioned by @chris just using a
.
is sufficient too.Re your question above about precision:
You are already working with long doubles .. I don't think internally you can change anything unless you use some special library, but you can certainly display more digits. E.g.,
will yield
Finally, as @edA-qa mort-ora-y reminds us, you can also cast values to certain types, but it matters when you do it. A simple example (note that the values end up as
float
after the assignment in any case sincev
is afloat
):