在 C++ 中保留两位小数的方法包括:1. 使用格式化字符串,如 fixed 和 setprecision;2. 使用流操作符,如 setw 和 setprecision;3. 使用数学函数,如 round 和 floor。
如何在 C++ 中保留两位小数
在 C++ 中,保留两位小数的方法有几种:
1. 使用格式化字符串
#include <iostream> #include <iomanip> using namespace std; int main() { double value = 123.4567; // 保留两位小数并四舍五入 cout << fixed << setprecision(2) << value << endl; // 保留两位小数并截断 cout << fixed << setprecision(2) << trunc(value) << endl; return 0; }
2. 使用流操作符
立即学习“C++免费学习笔记(深入)”;
#include <iostream> using namespace std; int main() { double value = 123.4567; // 保留两位小数并四舍五入 cout << setw(6) << setprecision(2) << value << endl; // 保留两位小数并截断 cout << setw(6) << setprecision(2) << int(value * 100) / 100.0 << endl; return 0; }
3. 使用数学函数
#include <iostream> #include <cmath> using namespace std; int main() { double value = 123.4567; // 保留两位小数并四舍五入 cout << round(value * 100) / 100.0 << endl; // 保留两位小数并截断 cout << floor(value * 100) / 100.0 << endl; return 0; }
以上就是c++++怎么保留两位小数的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号