一. C99開始支持使用round()系列函數(shù)處理四舍五入
頭文件與函數(shù)原型:
#include <math.h>
double round(double x);
long double roundl(long double x);
float roundf(float x);
long int lround(double x);
long int lroundl(long double x);
long int lroundf(float x);
特殊值的處理:
round(+-0) 返回 +-0
round(+-infinity) 返回 +-infinity
二. C++11開始支持double round(T x)函數(shù)
三. 在比較早的語言版本中需要自定義實現(xiàn),具體實現(xiàn)方式有:
- 遵循以下公式計算保留n位小數(shù)
比如給定3.141592這個數(shù)求其整數(shù)近似值或者保留一位、三位小數(shù)的近似值,可以寫成:
x = 3.141592;
// 保留整數(shù)
x0 = (int)(x + 0.5);
// 保留一位小數(shù)
x1 = (int)(x * 10 + 0.5) * 0.1;
// 保留三位小數(shù)
x3 = (int)(x * 1000 + 0.5) * 0.001;
實際計算出來的結(jié)果:
保留整數(shù):3
保留一位小數(shù):3.1
保留三位小數(shù):3.142