在C++中,有三种方法可以保留五位小数:

  1. 使用iomanip库中的setprecision()函数:
#include <iostream>
#include <iomanip>

int main() {
    double number = 3.141592653589793;

    std::cout << std::fixed << std::setprecision(5) << number << std::endl;

    return 0;
}

输出结果为:3.14159

  1. 使用printf()函数:
#include <iostream>
#include <cstdio>

int main() {
    double number = 3.141592653589793;

    printf("%.5f\n", number);

    return 0;
}

输出结果为:3.14159

  1. 使用stringstream类:
#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    double number = 3.141592653589793;

    std::stringstream ss;
    ss << std::fixed << std::setprecision(5) << number;

    std::cout << ss.str() << std::endl;

    return 0;
}

输出结果为:3.1415

怎么保留五位小数举例三种方法c++

原文地址: https://www.cveoy.top/t/topic/ihsX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录