简体   繁体   中英

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

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

Use setf and precision .

#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

This one does show "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. 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:

#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 . Don't forget to add #include <iomanip> in your code.

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. The setprecision allows setting the precision used for displaying floating-point values, it takes an integer argument.

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

You may unset fixed using cout.unsetf(ios::fixed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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