在 C++ 中保留小数点后两位有两种方法:使用流操纵符 std::fixed 和 std::setprecision(2)。使用四舍五入函数 round() 将数字乘以 100 后再除以 100。

如何使用 C++ 保留小数点后两位
在 C++ 中保留小数点后两位有两种主要方法:
方法 1:使用流操纵符
#includeint main() { double number = 123.4567; std::cout << std::fixed << std::setprecision(2) << number << std::endl; return 0; }
-
std::fixed告诉cout以固定点格式显示数字。 -
std::setprecision(2)设置要显示的小数位数。
方法 2:使用四舍五入函数
立即学习“C++免费学习笔记(深入)”;
#includeint main() { double number = 123.4567; number = round(number * 100) / 100; std::cout << number << std::endl; return 0; }
-
round()函数返回四舍五入到最接近整数值的数字。 - 我们通过将数字乘以 100,然后除以 100,来仅保留小数点后两位。
示例输出:
使用以上任何一种方法,示例输出都将为:
123.45










