round off problem
-
Hello, How to round a number into nearest integer in C++? Is there any function to do that? THX!!! :):):)
double a_bouble_val = 23,34;
int an_integer = (int)a_double_val;This small code will assign
an_integer
to 23.double a_bouble_val = 23,7;
int an_integer = (int)a_double_val;This, will assign
an_integer
to 24. Did I understand you? Rickard Andersson@Suza Computing C# and C++ programmer from SWEDEN! UIN: 50302279 E-Mail: nikado@pc.nu Speciality: I love C#, ASP.NET and C++! -
Hello, How to round a number into nearest integer in C++? Is there any function to do that? THX!!! :):):)
You can use
floor()
,ceil()
, or just cast to anint
eger. This code rounds a value to the nearest integer.int rounded = (int)(doubleval + 0.5);
CPUA 0x5041 Sonork 100.11743 Chicken Little "So it can now be written in stone as a testament to humanities achievments "PJ did Pi at CP"." Colin Davies Within you lies the power for good - Use it!
-
double a_bouble_val = 23,34;
int an_integer = (int)a_double_val;This small code will assign
an_integer
to 23.double a_bouble_val = 23,7;
int an_integer = (int)a_double_val;This, will assign
an_integer
to 24. Did I understand you? Rickard Andersson@Suza Computing C# and C++ programmer from SWEDEN! UIN: 50302279 E-Mail: nikado@pc.nu Speciality: I love C#, ASP.NET and C++!Rickard Andersson wrote: double a_bouble_val = 23,7;int an_integer = (int)a_double_val; This, will assign an_integer to 24. Actually, this will evaluate to 23. Casting a double to an int will always round to the whole number given (down for positive numbers, up for negative)
CPUA 0x5041 Sonork 100.11743 Chicken Little "So it can now be written in stone as a testament to humanities achievments "PJ did Pi at CP"." Colin Davies Within you lies the power for good - Use it!
-
Hello, How to round a number into nearest integer in C++? Is there any function to do that? THX!!! :):):)
It's a little more complicated if you are going to be dealing with both positive and negative numbers, as the floor() function moves the decimal number toward zero and the ceil() function moves the decimal number away from zero. The value of floor(-23.7) is -23, where rounded you probably would want -24. Adding 0.5 to the value before casting to an int works only for positive values, and not for negatives. There, you would have to subtract.
floor(-23.7 - 0.5) = floor(-24.2) = 24 floor( 23.7 + 0.5) = floor( 24.2) = 24
Dave "You can say that again." -- Dept. of Redundancy Dept. -
You can use
floor()
,ceil()
, or just cast to anint
eger. This code rounds a value to the nearest integer.int rounded = (int)(doubleval + 0.5);
CPUA 0x5041 Sonork 100.11743 Chicken Little "So it can now be written in stone as a testament to humanities achievments "PJ did Pi at CP"." Colin Davies Within you lies the power for good - Use it!