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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:47:41  来源:igfitidea点击:

How to output with 3 digits after the decimal point with C++ stream?

c++floating-pointiostream

提问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

Use setfand precision.

使用setfprecision

#include <iostream>

using namespace std;

int main () {
    double f = 3.14159;
    cout.setf(ios::fixed,ios::floatfield);
    cout.precision(3);
    cout << f << endl;
    return 0;
}

This prints 3.142

这打印 3.142

回答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 iomanipheader. 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 fixedand setprecisionchange the stream permanently so, if you want to localise the effects, you can save the information beforehand and restore it afterwards:

请注意,fixedsetprecision永久更改流,因此,如果您想本地化效果,您可以事先保存信息并在之后恢复它:

#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>您的代码。