保留小数点后1位
1.浮点数除法+四舍五入
#include <iostream> #include <iomanip> // 控制输出格式 #include <cmath> // 用于 round 函数 using namespace std; int main() { double a = 5; double b = 2; double result = a / b; // 保留一位小数并输出 cout << fixed << setprecision(1) << result << endl; return 0; }
2.先round再输出
round对小数点后一位四舍五入
round(1.5)=2.000000 round(1.56)=2.000000 round(-1.5)=-2.000000 round(-1.56)=-2.000000
保留一位小数
double result = 2.46; double rounded = round(result * 10) / 10; // round(24.6) = 25 → 25/10 = 2.5 cout << fixed << setprecision(1) << rounded << endl; // 输出 2.5 result = 2.44; rounded = round(result * 10) / 10; // round(24.4) = 24 → 24/10 = 2.4 cout << fixed << setprecision(1) << rounded << endl; // 输出 2.4
3.强制类型转换为浮点数
#include <iostream> #include <iomanip> using namespace std; int main() { int a = 5; int b = 2; double result = (double)a / b; cout << fixed << setprecision(1) << result << endl; return 0; }
4.不四舍五入
double truncated = (int)(result * 10) / 10.0; //保留小数点后一位
double truncated = (int)(result * 100) / 100.00; //保留小数点后两位
浙公网安备 33010602011771号