在 C++ 中,保留两位小数的方法如下:使用 std::fixed 和 std::setprecision使用格式化字符串使用 ostream::precision

如何使用 C++ 保留两位小数
在 C++ 中,可以使用以下方法保留两位小数:
使用 std::fixed 和 std::setprecision
<code class="cpp">#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double number = 12.3456;
// 保留两位小数
cout << fixed << setprecision(2) << number << endl;
return 0;
}</code>使用格式化字符串
立即学习“C++免费学习笔记(深入)”;
<code class="cpp">#include <iostream>
using namespace std;
int main() {
double number = 12.3456;
// 保留两位小数
cout << fixed << setprecision(2) << number << endl;
return 0;
}</code>使用 ostream::precision
<code class="cpp">#include <iostream>
using namespace std;
int main() {
double number = 12.3456;
// 保留两位小数
cout.precision(2);
cout << number << endl;
return 0;
}</code>以上方法都可以将浮点数 number 保留两位小数,输出结果为 "12.35"。
以上就是c++++如何保留两位小数的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号