四舍五入:是一种精确度的计数保留法。即保留三位小数,只看第四位小数,不看第五位。
所以3.14445保留三位小数为3.144
一:自己编写函数。
二:使用系统自带的函数即可。
系统的printf(),round()都可以。
round(x)返回x的四舍五入整数值。
代码如下:
#include<iostream>
#include<math.h>
using namespace std;
int main(){
float a=3.14454;
cout<<a;//输出:3.14454
printf("\t%.5f",a);//输出:3.14454
printf("\t%.3f\n",a);//输出:3.145
a=round(a*1000)/1000.0;
cout<<a;//输出:3.145
printf("\t%.5f",a);//输出:3.14500
printf("\t%.3f\n\n",a);//输出:3.145
float b=3.14445;
cout<<b;//输出:3.14445
printf("\t%.5f",b);//输出:3.14454
printf("\t%.3f\n",b);//输出:3.144
b=round(b*1000)/1000.0;
cout<<b;//输出:3.144
printf("\t%.5f",b);//输出:3.14400
printf("\t%.3f\n",b);//输出:3.144
return 0;
}