gpt4 book ai didi

c++ - 如何输出计算到小数点后两位的整数?

转载 作者:行者123 更新时间:2023-11-27 22:39:26 24 4
gpt4 key购买 nike

很容易输出一个计算到小数点后两位的 double 值。代码片段如下:

cout.setf(ios_base::showpoint);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.precision(2);
cout << 10000000.2 << endl; // output: 10000000.20
cout << 2.561452 << endl; // output: 2.56
cout << 24 << endl; // output: 24 but I want 24.00, how to change my code?

如何输出计算到小数点后两位的整数?我想要 24.00 作为输出。

最佳答案

这取决于你的 24 是多少。

如果它是一个硬编码值,你可以这样写:

std::cout << 24.00 << std::endl;

如果是整型变量,这样写:

std::cout << static_cast<double>(myIntegerVariable) << std::endl;

不要使用任何建议的方法,例如添加“.00”,因为如果您想稍后更改精度,这会破坏您的代码。

关于c++ - 如何输出计算到小数点后两位的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50324530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com