c++中有这三个函数用来处理小数向整数的转换:
2.1 2.6 -2.1 -2.6
floor : 不大于自变量的最大整数 2 2 -3 -3
ceil :不小于自变量的最大整数 3 3 -2 -2
2.1 2.6 -2.1 -2.6
floor : 不大于自变量的最大整数 2 2 -3 -3
ceil :不小于自变量的最大整数 3 3 -2 -2
round:四舍五入到最邻近的整数 2 3 -2 -3
话不多说上代码:
int main(){ float a = 17.8836; printf("%.3f\n", a);//输出:17.884 float b = 17.8836; b = round(b * 1000) / 1000; cout << b << endl; //输出17.884 float c = 17.8836; c = floor(c * 1000 + 0.5) / 1000; cout << c << endl; //输出17.884 float d = 17.8831; d = floor(d * 1000 + 0.5) / 1000; cout << d << endl; //输出17.883 getchar(); return 1; }