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

如何保留 C++ 小数点后一位
直接方法: 使用 std::fixed 和 std::setprecision 函数。
<code class="cpp">#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double num = 123.456;
    // 保留小数点后一位
    cout << fixed << setprecision(1) << num << endl;  // 输出: 123.5
    return 0;
}</code>使用 std::to_string:
<code class="cpp">#include <iostream>
#include <sstream>
using namespace std;
int main() {
    double num = 123.456;
    stringstream ss;
    // 保留小数点后一位
    ss << fixed << setprecision(1) << num;
    string str = ss.str();
    cout << str << endl;  // 输出: 123.5
}</code>使用 std::round:
立即学习“C++免费学习笔记(深入)”;
<code class="cpp">#include <iostream>
#include <cmath>
using namespace std;
int main() {
    double num = 123.456;
    // 四舍五入到小数点后一位
    num = round(num * 10) / 10;
    cout << num << endl;  // 输出: 123.5
}</code>使用 printf:
<code class="cpp">#include <iostream>
#include <cstdio>
using namespace std;
int main() {
    double num = 123.456;
    // 保留小数点后一位
    printf("%.1f\n", num);  // 输出: 123.5
}</code>以上就是c++++如何保留小数点后一位的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号