// 四舍五入并保留n位小数,返回结果的整数形式
unsigned int round_float(float f, unsigned char n) {
float scale = 1;
for (unsigned char i = 0; i < n; i++) {
scale *= 10;
}
return (unsigned int)(f * scale + 0.5f);
}
使用示例
float f = 3.14159f;
unsigned int result = round_float(f, 2); // 保留2位小数,结果为314
|