當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ iomanip setpricision()用法及代碼示例


C++中的iomaip庫的setprecision()方法用於基於為此方法的參數指定的精度來設置ios庫浮點精度。

用法:

setprecision(int n)

參數:此方法接受n作為參數,它是要設置浮點精度的整數參數。


返回值:此方法不返回任何內容。它僅充當流操縱器。

示例1:

// C++ code to demonstrate 
// the working of setprecision() function 
  
#include <iomanip> 
#include <ios> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
  
    // Initializing the decimal 
    double num = 3.142857142857; 
  
    cout << "Before setting the precision: \n"
         << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using"
         << " setprecision to 5: \n"
         << setprecision(5); 
  
    cout << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using
            "<<" setprecision to 9 : \n " 
         << setprecision(9); 
  
    cout << num << endl; 
  
    return 0; 
}
輸出:
Before setting the precision: 
3.14286
Setting the precision using setprecision to 5: 
3.1429
Setting the precision using setprecision to 9: 
3.14285714

示例2:

// C++ code to demonstrate 
// the working of setprecision() function 
  
#include <iomanip> 
#include <ios> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
  
    // Initializing the decimal 
    double num = 3.14; 
  
    cout << fixed; 
  
    cout << "Before setting the precision: \n"
         << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using"
         << " setprecision to 5: \n"
         << setprecision(5); 
  
    cout << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using"
         << " setprecision to 9: \n"
         << setprecision(9); 
  
    cout << num << endl; 
    return 0; 
}
輸出:
Before setting the precision: 
3.140000
Setting the precision using setprecision to 5: 
3.14000
Setting the precision using setprecision to 9: 
3.140000000

參考: http://www.cplusplus.com/reference/iomanip/setprecision/



相關用法


注:本文由純淨天空篩選整理自guptayashgupta53大神的英文原創作品 iomanip setpricision() function in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。