Help with rounding

Started by
3 comments, last by BSMonkey 20 years ago
Ok. I know this is really easy but I just cant find it in my book and my compiler index isnt working. So heres the question. How can I round a double to an int? like 2.6 to 3? Oh and this is for C++ using visual studio .net 2003 Thanks for the help in advance. These are the two lines where Im using it maybe there is something wrong with them. Monster->LocationY = Monster->LocationY + round( ( double )Slope->SlopeY / Slope->SlopeX ); Monster->LocationX = Monster->LocationX + round( ( double )Slope->SlopeX / Slope->SlopeY ); I dont think so though the compiler error is: error C3861: ''round'': identifier not found, even with argument-dependent lookup
Advertisement
quote:Original post by BSMonkey
How can I round a double to an int? like 2.6 to 3?


The standard c library has ceil and floor that you can use to get a float/double that represents just the integer part. You will have to create your own round function (probably using ceil and/or floor ).

float float_number = 1.01;float floored_number = floor( float_number );// floored_number == 1.0float ceiled_number = ceil( float_number );// ceiled_number == 2.0int int_number = static_cast( float_number );// int_number == 1 

quote:Original post by BSMonkey
How can I round a double to an int? like 2.6 to 3?



You can add 0.5 to the number you want to round, then cast to int.
quote:Original post by rypskar
You can add 0.5 to the number you want to round, then cast to int.


If you need a method that works for negative numbers:
inline double round( double x ){    return floor( x + 0.5 );}  

John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
OK cool man that works greate thanks for the help. I hate it when I get stuck on this little stuff it just takes away my motivation but now I got it back so I can write a few more pages of code and hopefully I wont get stuck on something stupid

This topic is closed to new replies.

Advertisement