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 support@ccsinfo.com

round numbers

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



Joined: 12 Jul 2007
Posts: 32

View user's profile Send private message

round numbers
PostPosted: Wed Feb 27, 2008 4:52 am     Reply with quote

Hi,
how can I round numbers, so that 10.3 is 10 and 10.7 is 11?
abs() returns always 10.

Thanks!
Ttelmah
Guest







PostPosted: Wed Feb 27, 2008 5:30 am     Reply with quote

Abs, just removes the sign. If you are getting '10', it is not because of 'abs' at all, but because you are putting the result into an integer, which removes the fractional part. Abs on it's own, won't do this...
Now, question is whether you need to handle -ve numbers as well?.
For +ve numbers:

result = (int16)(val+0.499999);

Will give normal 4/5 rounding, assuming the result will fit in an int16.

For full numeric range:

result = (signed int32)((val>0.0)?(val+.4999999):(val-0.4999999));

Will work for the entire range of a signed int32.

So, generating a declare for this:
#define round45(x) (signed int32)((x>=0.0)?(x+.4999999):(x-0.4999999))

will allow you to have:

result = round45(val);

and should do what you want.

Best Wishes
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