C++ setprecision(3): Formatting Decimal Places for Output
C++ setprecision(3): Controlling Decimal Places in Output
'setprecision(3)' is a manipulator in C++ used to specify the number of decimal places to be displayed after the decimal point. It is commonly employed with the 'iomanip' header file to format output in C++ programs.
For instance, if you have a float variable 'x' with a value of 3.14159 and apply 'setprecision(3)', the output will be 3.142 (rounded to 3 decimal places).
Example Code Snippet:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float x = 3.14159;
cout << setprecision(3) << x << endl;
return 0;
}
Output:
3.14
This code snippet demonstrates how 'setprecision(3)' effectively controls the decimal places displayed in the output. By including the 'iomanip' header file and using the manipulator within the 'cout' stream, you can achieve the desired level of precision in your C++ programs.
原文地址: https://www.cveoy.top/t/topic/oTRB 著作权归作者所有。请勿转载和采集!