【发布时间】:2016-06-10 02:15:45
【问题描述】:
我需要有关如何在 C++ 中格式化输出以显示小数位(如果有)或显示整个整数(如果没有小数点可显示)的帮助。
it should show 95.7 // When there is decimal
it should show 90 // When there is no decimal
我写道:
cout << setprecision(1) << fixed;
它没有给我预期的输出。它不是打印 90,而是打印 90.0
【问题讨论】:
-
那么你的问题是什么?你面临什么错误?
-
简单
std::cout << 95.7 << ' ' << 90.0 << '\n';默认显示您请求的值。你真的连代码都不看吗?如果您的代码不起作用,请将其发布并向我们展示您实际得到的输出。 -
当我写的时候:cout
-
当你知道一个数字没有十进制值时,你不应该使用
std::setprecision(1),因为它会强制任何数字在小数点右侧有1位数字。您必须首先确定该数字是否具有十进制值。如果有,请使用std::setprecision(1)。否则,不要使用它。 -
@Allen,您确定您使用的是
std::cout而不是printf()?
标签: c++ floating-point iomanip