q****4 发帖数: 1 | 1 hi,
any round function or similar things in C/C++?
such as round(5.5) = 6; round(6.4) =6...
thanks, |
P********e 发帖数: 2610 | 2 inline int round(double r)
{
if (r > 0)
return (int)(r+0.5);
else return (int)(r-0.5);
}
【在 q****4 的大作中提到】 : hi, : any round function or similar things in C/C++? : such as round(5.5) = 6; round(6.4) =6... : thanks,
|
d*****a 发帖数: 110 | 3 ROUND(3) Linux Programmer's Manual ROUND(
3)
NAME
round, roundf, roundl - round to nearest integer, away from zero
SYNOPSIS
#include
double round(double x);
float roundf(float x);
long double roundl(long double x);
DESCRIPTION
These functions round x to the nearest integer, but round halfway
cases
away from zero (regardless of the current rounding direction),
instead
of to the nearest even intege |
t****t 发帖数: 6806 | 4 你不能用floor(r+0.5)么?
【在 P********e 的大作中提到】 : inline int round(double r) : { : if (r > 0) : return (int)(r+0.5); : else return (int)(r-0.5); : }
|
P********e 发帖数: 2610 | 5 也可以,你这个调用cmath了,速度肯定慢,如果是大量数学操作,差别挺大的
【在 t****t 的大作中提到】 : 你不能用floor(r+0.5)么?
|
t****t 发帖数: 6806 | 6 你还真以为编译器现在落后到这种程度么.
【在 P********e 的大作中提到】 : 也可以,你这个调用cmath了,速度肯定慢,如果是大量数学操作,差别挺大的
|
P********e 发帖数: 2610 | 7 个人感觉吧,也可能是错的
不过我反正基本能不用cmath就不用
【在 t****t 的大作中提到】 : 你还真以为编译器现在落后到这种程度么.
|
z******i 发帖数: 59 | 8 This code might be very slow.
It will be translated to something like the following assemly code.
fldcw [ebp-4] ;Write new value to FCW
fistp DWORD PTR [ebp-16] ;Convert fvalue to integer
;and pop stack
fldcw [ebp-12] ;Restore FCW to its
;original state
It is a serial code in CPU because it changes FPU's control word.
A better solution is using SSE, 4 float one time
【在 P********e 的大作中提到】 : inline int round(double r) : { : if (r > 0) : return (int)(r+0.5); : else return (int)(r-0.5); : }
|