C++四舍五入保留整数
方案一
使用四舍五入函数
函数原型
C99
double round (double x);
float roundf (float x);
long double roundl (long double x);
double round (double x);
float round (float x);
long double round (long double x);
double round (T x); // additional overloads for integral types
方案二
实现round函数
若参数为正数, 返回为参数值加 0.5 向下取整数, 若参数为负数, 返回为参数值减 0.5 向上取整数 。
int round_double(double number)
{
return (number > 0.0) ? (number + 0.5) : (number - 0.5);
}
或
// floor向下取整数
// ceil向上取整数
int round_double(double number)
{
return (number > 0.0) ? floor(number + 0.5) : ceil(number - 0.5);
}
原理
C++ 采取向0取整的方式使浮点数转换为整数。 事实上,库函数也是采用该方式实现
更多
参考文献
C++ round函数
C++的四舍五入函数
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈