c++中如何只保留float型的小数点后两位

float spd = 22.518744;
char buf[10];
sprintf(buf, "%.2f", spd);
sscanf(buf, "%f", &spd);

记录一下,有时候我们需要float类型只保留两个有效小数,但是在实际应用中会发现一些现象

如:1.5 在实际中为1.49999998 等等

还有一个常用的方法同时进行四舍五入:

float ff = 36.51647;
ff = ( (float)( (int)( (ff + 0.005) * 100 ) ) ) / 100;

但是有时候效果也不理想

猜你喜欢

转载自blog.csdn.net/zb774095236/article/details/89493283