卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章70024本站已运行4223

c++如何保留小数点后一位

直接方法有四种:使用 std::fixed 和 std::setprecision 函数。使用 std::to_string。使用 std::round。使用 printf。

c++如何保留小数点后一位

如何保留 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>
卓越飞翔博客
上一篇: c++如何保留小数点后一位输出
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏