LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

A strange behaviour in casting...

Look at this sample code:

int b, d;
double c, coef;

coef = 0.6;
c = 100.0 * coef;
b = (int) c;
d = (int)(100.0 * coef);
printf ("DOUBLE:\t\t%0.f\n", 100.0 * coef); // Print the integer
portion of double
printf ("INT:\t\t%d\n", b); // Print double value casted as
integer
printf ("INT (cast):\t\t%d\n", d); // The same but casting the result of
a calculus

And look at the output generated:

DOUBLE: 60
INT: 60
INT (cast): 59

Can anyone explain me that strange behaviour in converting double values?
TIA
Roberto
0 Kudos
Message 1 of 2
(3,137 Views)
I think you are seeing the effects of floating point math, where the processor
may actually represent 60.0 as 59.9999.... I tried your code in CVI, and
got the same results. It looks like what you expect to be 60.0 might actually
59.9999... on the right side of an '=', or before it gets formatted in a
printf() statement. The (int) cast should truncate anything to the right
of the decimal point, so it seems that is why the expression (int)(100.0
* coef) may actually be (int)(59.9999...) which gets truncated to 59 before
being assigned to d. If I try

printf("%10.4e\n", 60.0-(100.0 * coef));

I get 2.2204e-15, which means to me that the value of (100.0 * coef) is actually
very slightly less than 60. Hope this helps.

Dave

"Roberto" wrote:
>Look at
this sample code:>>int b, d;>double c, coef;>>coef = 0.6;>c
= 100.0 * coef;>b = (int) c;>d = (int)(100.0 * coef);>printf ("DOUBLE:\t\t%0.f\n",
100.0 * coef); // Print the integer>portion of double>printf ("INT:\t\t%d\n",
b); // Print double value casted as>integer>printf ("INT (cast):\t\t%d\n",
d); // The same but casting the result of>a calculus>>And look at the
output generated:>>DOUBLE: 60>INT: 60>INT (cast): 59>>Can anyone
explain me that strange behaviour in converting double values?>TIA>Roberto>>
0 Kudos
Message 2 of 2
(3,137 Views)