C++ 如何用C++流输出小数点后3位数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8554441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to output with 3 digits after the decimal point with C++ stream?
提问by Alex Lapchenko
Given a variable of float type, how to output it with 3 digits after the decimal point, using iostream in C++?
给定一个float类型的变量,如何在C++中使用iostream输出小数点后3位?
回答by dasblinkenlight
回答by mask8
This one does show "13.141"
这个确实显示“13.141”
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double f = 13.14159;
cout << fixed;
cout << setprecision(3) << f << endl;
return 0;
}
回答by paxdiablo
You can get fixed number of fractional digits (and many other things) by using the iomanip
header. For example:
您可以通过使用iomanip
标题获得固定数量的小数位数(以及许多其他内容)。例如:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589;
std::cout << std::fixed << std::setprecision(2) << pi << '\n';
return 0;
}
will output:
将输出:
3.14
Note that both fixed
and setprecision
change the stream permanently so, if you want to localise the effects, you can save the information beforehand and restore it afterwards:
请注意,fixed
和setprecision
永久更改流,因此,如果您想本地化效果,您可以事先保存信息并在之后恢复它:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589;
std::cout << pi << '\n';
// Save flags/precision.
std::ios_base::fmtflags oldflags = std::cout.flags();
std::streamsize oldprecision = std::cout.precision();
std::cout << std::fixed << std::setprecision(2) << pi << '\n';
std::cout << pi << '\n';
// Restore flags/precision.
std::cout.flags (oldflags);
std::cout.precision (oldprecision);
std::cout << pi << '\n';
return 0;
}
The output of that is:
其输出是:
3.14159
3.14
3.14
3.14159
回答by uneet7
If you want to print numbers with precision of 3 digits after decimal, just add the following thing before printing the number cout << std::setprecision(3) << desired_number
. Don't forget to add #include <iomanip>
in your code.
如果要打印精度为小数点后 3 位的数字,只需在打印数字之前添加以下内容cout << std::setprecision(3) << desired_number
。不要忘记添加#include <iomanip>
您的代码。