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

如何使用 C++ 保留小数点后两位
在 C++ 中保留小数点后两位有两种主要方法:
方法 1:使用流操纵符
<code class="cpp">#include <iomanip>
int main() {
double number = 123.4567;
std::cout << std::fixed << std::setprecision(2) << number << std::endl;
return 0;
}</code>std::fixed 告诉 cout 以固定点格式显示数字。std::setprecision(2) 设置要显示的小数位数。方法 2:使用四舍五入函数
立即学习“C++免费学习笔记(深入)”;
<code class="cpp">#include <cmath>
int main() {
double number = 123.4567;
number = round(number * 100) / 100;
std::cout << number << std::endl;
return 0;
}</code>round() 函数返回四舍五入到最接近整数值的数字。示例输出:
使用以上任何一种方法,示例输出都将为:
<code>123.45</code>
以上就是c++++如何保留小数点后两位的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号