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

半腔热情 提交于 2019-11-27 16:04:19

问题


Given a variable of float type, how to output it with 3 digits after the decimal point, using iostream in C++?


回答1:


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




回答2:


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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/8554441/how-to-output-with-3-digits-after-the-decimal-point-with-c-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!