直接方法有四种:使用 std::fixed 和 std::setprecision 函数。使用 std::to_string。使用 std::round。使用 printf。
如何保留 C++ 小数点后一位
直接方法: 使用 std::fixed 和 std::setprecision 函数。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double num = 123.456;
// 保留小数点后一位
cout <p><strong>使用 std::to_string:</strong></p>
<pre class="brush:php;toolbar:false">#include <iostream>
#include <sstream>
using namespace std;
int main() {
double num = 123.456;
stringstream ss;
// 保留小数点后一位
ss <p><strong>使用 std::round:</strong></p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p>
<pre class="brush:php;toolbar:false">#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num = 123.456;
// 四舍五入到小数点后一位
num = round(num * 10) / 10;
cout <p><strong>使用 printf:</strong></p>
<pre class="brush:php;toolbar:false">#include <iostream>
#include <cstdio>
using namespace std;
int main() {
double num = 123.456;
// 保留小数点后一位
printf("%.1fn", num); // 输出: 123.5
}</cstdio></iostream>