C/C++輸出那點小事


C/C++控制輸出時有時有控制精度的問題,現總結如下(這時C寫法更簡單些):

1.setprecision(n) 默認設置輸出的數字的總位數為n,包含整數和小數部分;

2.setiosflags(ios::fixed) 默認輸出6位,必須與setprecision(n)配合使用,用來控制小數位數,不夠補0;

3.resetiosflags(ios::fixed) 取消精度的設置。

直接上代碼:

#include<iostream> 
#include<iomanip> // 精度控制頭文件 
using namespace std; 
int main() 
{ 
    const double value=12.3456789; 
    // C輸出方式printf()函數 
    printf("%lf\n",value); // double輸出為 12.3456789:遵循IEEE標准的8字節(64位)的double能表示的有效數字的位數是:15~16
    // C++輸出方式cout函數 
    cout<<value<<endl; // 默認以6精度,所以輸出為 12.3457 
    cout<<setprecision(4)<<value<<endl; // 改成4精度,所以輸出為12.35 
    cout<<setprecision(8)<<value<<endl; // 改成8精度,所以輸出為12.345679
    // C語言控制精度方式: 
    printf("%.4lf\n",value); 
    // C++第一種方式: 
    cout<<fixed<<setprecision(4)<<value<<endl; // 加了fixed意味着是固定點方式顯示,所以這里的精度指的是小數位,輸出為12.3457 
    
    cout<<value<<endl; // fixed和setprecision的作用還在,依然顯示12.3457 
    cout.unsetf(ios::fixed); // 去掉了fixed,所以精度恢復成整個數值的有效位數,顯示為12.35 
    cout<<value<<endl; 
    cout.precision(6); // 恢復成原來的樣子,輸出為12.3457 
    cout<<value<<endl;
    // C++第二種方式:
    cout<<setiosflags(ios::fixed)<<setprecision(5)<<value<<endl;  // 輸出為12.34568,小數位數是5位,不夠補0
    cout<<resetiosflags(ios::fixed); // 取消精度的設置
    system("pause"); 
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM