1. 程式人生 > >c++控制輸出浮點型格式 小數點後位數或者整個浮點型數字的有效數字

c++控制輸出浮點型格式 小數點後位數或者整個浮點型數字的有效數字

int main()
{
    float a = float (4) / 8;
    float b = float(12 / 8);
    float c = 545451.01;
    cout << "a = "<< a <<endl;
    cout << "b = "<< b << endl;
    cout << "c = " << c << endl;
    cout<<setprecision(3)<<12345.0<<endl;
    cout << setiosflags(ios::fixed) << setprecision(1) << "c = " << c << endl;
    cout << resetiosflags(ios::fixed);//取消固定格式輸出 
    cout <<setprecision(6); 
    cout << "b = "<< b << endl;
    cout << "c = " << c << endl;
    cout << setprecision(1) << "c = " << c << endl;    
    cout << setprecision(1) << "b = " << b << endl;
    system("pause");
    return 0;
    }

結果為:

這裡面需要注意的setiosflags(ios::fixed)這句話,不錯

如果和setprecision(n)一起用的話就是控制小數點後的位數了。

如果單獨用setprecision(n),實際上是控制浮點數的有效數字個數

另外如果設定了setiosflags(ios::fixed)的話,需要人為的取消,要不然的話這個設定一直有效

取消就用resetiosflags(ios::fixed)