C++中iomaip庫的setprecision()方法用於根據為此方法的參數指定的精度來設置ios庫浮點精度。
setprecision(int n)
參數:此方法接受n作為參數,該參數是要設置浮點精度的整數參數。返回值:此方法不返回任何內容。它僅用作流操縱器。示例1:
C++
// 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++
// 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/
相關用法
- C++ iomanip resetiosflags()用法及代碼示例
- C++ iomanip setfill()用法及代碼示例
- C++ iomanip setbase()用法及代碼示例
- C++ iomanip setw()用法及代碼示例
- C++ iomanip setiosflags()用法及代碼示例
- C++ wcscpy()用法及代碼示例
- C++ wcscmp()用法及代碼示例
- C++ quick_exit()用法及代碼示例
- C++ btowc()用法及代碼示例
- C++ wcsspn()用法及代碼示例
- C++ wcslen()用法及代碼示例
- C++ conj()用法及代碼示例
- C++ norm()用法及代碼示例
- C++ ios fail()用法及代碼示例
- C++ ios bad()用法及代碼示例
- C++ ios setstate()用法及代碼示例
- C++ ios good()用法及代碼示例
- C++ ios eof()用法及代碼示例
注:本文由純淨天空篩選整理自guptayashgupta53大神的英文原創作品 iomanip setprecision() function in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。