CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

Multiplication of different types

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
Tagge



Joined: 23 Aug 2005
Posts: 93

View user's profile Send private message Visit poster's website

Multiplication of different types
PostPosted: Fri Jan 05, 2007 4:29 am     Reply with quote

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

View user's profile Send private message

PostPosted: Fri Jan 05, 2007 7:52 am     Reply with quote

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
Code:
y = (x * z) + 0.5;
Ken Johnson



Joined: 23 Mar 2006
Posts: 197
Location: Lewisburg, WV

View user's profile Send private message

PostPosted: Fri Jan 05, 2007 8:01 am     Reply with quote

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
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group