#include <iostream> #include <iomanip> using namespace std; int main(){ double sum = 0; double PI = 3.1415926; sum+=1; cout<<setprecision(4)<<PI<<endl;//保留4位有效数字 cout<<fixed<<setprecision(2)<<sum<<endl;//保留两位小数 cout<<fixed<<setprecision(4)<<PI<<endl;//保留四位小数 return 0; }
记住:fixed有覆盖的功能。如果把第二句输出放在第一句前面,那两个输出的结果是一致的。
#include <iostream> #include <iomanip> using namespace std; int main(){ double sum = 0; double PI = 3.1415926; sum+=1; cout<<fixed<<setprecision(2)<<sum<<endl;//保留两位小数 cout<<setprecision(4)<<PI<<endl;//原先的功能是保留4位有效数字,但因fixed已经出现,所以这里的功能也就变成了保留四位小数。 cout<<fixed<<setprecision(4)<<PI<<endl;//保留四位小数 return 0; }
另外:当使用setprecision去处理小数的时候,会自动的四舍五入。
注意:使用的时候。必须要加头文件<iomanip>。
不足的,请大家评论指导。