c++中小数点显示几位的问题

来源:互联网 发布:华南师范大学 网络缴费 编辑:程序博客网 时间:2024/04/20 16:48

参考自http://blog.csdn.net/yayingstar/article/details/18525239

http://blog.csdn.net/edricbjtu/article/details/41082597


#include <iostream>#include <iomanip>using namespace std;int main(){    //以下所有保留小数的情形都考虑了四舍五入的情况    double t = 1.125;    //以下语句中的2包括小数点前的数字1    cout<<setprecision(2)<<t<<endl;    //虽然5>3,但是输出结构不用0来凑齐    cout<<setprecision(5)<<t<<endl;    //注意:一旦在下一条语句中加入了格式控制fixed,那么在后面的cout语句中    //除非显示的改变格式控制,否则就默认按照前面规定的fixed格式输出    cout<<fixed<<setprecision(2)<<t<<endl;    //以下两条语句的输出格式是一样的    cout<<setprecision(5)<<t<<endl;    cout<<fixed<<setprecision(5)<<t<<endl;    //显示修改了输出控制方式,以下两条语句的输出格式也是一样的    cout<<scientific<<setprecision(2)<<t<<endl;    cout<<setprecision(2)<<t<<endl;    return 0;}
double t = 11.1234;cout << setprecision(2) << t<<endl;cout << setprecision(3) << t<<endl;cout << setprecision(7) << t <<endl;cout.setf(ios::fixed);cout << setprecision(7) << t << endl;cout << setprecision(1) << t << endl;cout << setprecision(2) << t << endl;cout.unsetf(ios::fixed);cout << setprecision(1) << t << endl;cout << setprecision(2) << t << endl;

运行结果如图: