C++ 输出保留一位小数的浮点数
在 C++ 中,可以使用流控制符来设置输出精度,从而保留特定位数的小数。以下是一个示例代码,展示如何保留一位小数输出浮点数:
#include <iostream>
#include <iomanip>
int main() {
double num = 3.14159;
std::cout << std::fixed << std::setprecision(1) << num << std::endl;
return 0;
}
输出:
3.1
在这个示例中,通过 std::setprecision(1) 设置保留一位小数,然后将浮点数 num 作为输出流的一部分,通过 std::cout 进行输出。
请注意,浮点数的显示方式也受到当前的精度设置和舍入规则的影响,所以输出结果可能因环境而异。
原文地址: http://www.cveoy.top/t/topic/7XA 著作权归作者所有。请勿转载和采集!