简体   繁体   English

如何用C++流输出小数点后3位数字?

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

给定一个float类型的变量,如何在C++中使用iostream输出小数点后3位?

Use setf and 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

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;
}

You can get fixed number of fractional digits (and many other things) by using the iomanip header.您可以使用iomanip标头获得固定数量的小数位数(以及许多其他内容)。 For example:例如:

#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:请注意, 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

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 .如果要打印小数点后 3 位精度的数字,只需在打印数字cout << std::setprecision(3) << desired_number之前添加以下cout << std::setprecision(3) << desired_number Don't forget to add #include <iomanip> in your code.不要忘记在代码中添加#include <iomanip>

In general, precision is the maximum number of digits displayed.通常,精度是显示的最大位数。 The manipulator fixed will set up the output stream for displaying values in fixed format.操纵器固定将设置输出流以固定格式显示值。 In fixed the precision is the number of digits after the decimal point.fixed中精度是小数点后的位数。 The setprecision allows setting the precision used for displaying floating-point values, it takes an integer argument. setprecision允许设置用于显示浮点值的精度,它需要一个整数参数。

cout << fixed;
cout << setprecision(3) << f << endl;

You may unset fixed using cout.unsetf(ios::fixed)您可以使用cout.unsetf(ios::fixed)取消固定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM