View previous topic :: View next topic |
Author |
Message |
Tagge
Joined: 23 Aug 2005 Posts: 93
|
Multiplication of different types |
Posted: Fri Jan 05, 2007 4:29 am |
|
|
Hi out there, and a bugless continuing to the new year.
Im wondering about how CCS handles multiplication of different types as:
Code: |
sint32 x,y;
float z;
x=99;
z=0.31;
y=x*z;
|
what is y?
I would like it to be 31, but is it?
I could test it but Im sure someone already has..
Have a nice day |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Fri Jan 05, 2007 7:52 am |
|
|
0.31 * 99 = 30.69
All correct C compilers will truncate the result when assigning to an integer, so your example will yield y=30.
To get 31 as a result you will have to round the intermediate value
|
|
|
Ken Johnson
Joined: 23 Mar 2006 Posts: 197 Location: Lewisburg, WV
|
|
Posted: Fri Jan 05, 2007 8:01 am |
|
|
Correct
More detail: to evaluate x*z, the compiler will first convert x to float, then multiply. The result of the expression on the right is float. To assign the value of the expression on the right to y (int), the compiler will truncate the result.
The float value on the right is always truncated when assigned to an int, but, by adding 0.5 first, you are rounding the result in accordance to the rounding rules we learned in school (many, many years ago).
Ken |
|
|
|