跳转至

浮点数

浮点类型

double price = 0.0;     // 双精度浮点数(常用)
float  price = 0.0f;    // 单精度浮点数(少用)

整数 vs 浮点数

int a = 10 / 3;      // → 3(整数除法,舍去小数)
double b = 10.0 / 3; // → 3.3333...(浮点数除法)
int c = 10.0 / 3;    // ⚠️ 警告:把 double 赋值给 int 会丢失精度

printf 格式化浮点数

double price = 12.3456;
printf("%%f\n", price);      // 输出: 12.345600
printf("%%.2f\n", price);    // 输出: 12.35(保留两位小数)
printf("%%7.2f\n", price);   // 输出: "  12.35"(总宽度 7,右对齐)

浮点数运算的精度问题

⚠️ 浮点数不是精确的,不要用 == 直接比较

double x = 0.1 + 0.2;   // 实际是 0.30000000000000004