Why use showpoint when you can use setprecision fixed?

杀马特。学长 韩版系。学妹 提交于 2021-02-07 08:36:54

问题


I don't quite understand the purpose of showpoint, i know it forces to show a decimal point, but having "cout << setprecision << fixed" is enough without the use of showpoint.

Can you show me an example where showpoint is a must have?


回答1:


When covering a large range of values it may be desirable to have the formatting logic to switch between the use of fixed point and scientific notation while still requiring a decimal point. If you look at the output of this example you'll see that it isn't just fixed point notation:

#include <iostream>

int main() {
    for (double value(1e15), divisor(1); divisor < 1e20; divisor *= 10) {
        std::cout << std::noshowpoint << (value / divisor) << '\t'
                  << std::showpoint << (value / divisor)
                  << '\n';
    }
}

This yields the output

1e+15   1.00000e+15
1e+14   1.00000e+14
1e+13   1.00000e+13
1e+12   1.00000e+12
1e+11   1.00000e+11
1e+10   1.00000e+10
1e+09   1.00000e+09
1e+08   1.00000e+08
1e+07   1.00000e+07
1e+06   1.00000e+06
100000  100000.
10000   10000.0
1000    1000.00
100 100.000
10  10.0000
1   1.00000
0.1 0.100000
0.01    0.0100000
0.001   0.00100000
0.0001  0.000100000



回答2:


If the precision is 0 and showpoint is not used, no decimal-point appears, else it does appear:

#include <iostream>
#include <iomanip>

int
main()
{
    double pi = 2646693125139304345./842468587426513207.;
    std::cout << std::fixed << std::setprecision(0);
    std::cout << pi << '\n';
    std::cout << std::showpoint;
    std::cout << pi << '\n';
}

Should output:

3
3.


来源:https://stackoverflow.com/questions/28552005/why-use-showpoint-when-you-can-use-setprecision-fixed

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