C++中iomaip库的setprecision()方法用于根据指定为该方法参数的精度来设置ios库浮点精度。
句法:
setprecision(int n)
参数:此方法接受n作为参数,它是要设置浮点精度的整数参数。
返回值:此方法不返回任何内容。它仅充当流操纵器。
范例1:
C++
// C++ code to demonstrate
// the working of setprecision() function
#include
#include
#include
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;
}
C++
// C++ code to demonstrate
// the working of setprecision() function
#include
#include
#include
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.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
#include
#include
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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。