c - 拆分两位数

标签 c floating-point decimal

我尝试拆分任意数量的两位数字,并在两个不同的变量中得到结果。我遇到了一个特定数字的问题:23

int root = 23;
float div = (float)root/10.0; // div = 23.0/10.0 = 2.3

int left = (int)div; // left = 2
int right = ((float)div - (float)left) * 10.0; // right = (2.3 - 2) * 10.0 = 0.3 * 10.0 = 3

printf("%d", right); // 2, why ?

有很多 float-to-int 操作,我在最终结果上遇到了一些麻烦。我是不是错过了或没听懂什么?

最佳答案

由于 0.3 可能无法准确地用二进制表示,因此您最终得到 2.9999……当转换为 int 时,它变成了 2

相反:

int root = 23;
int left = root / 10;
int right = root % 10;

关于c - 拆分两位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767593/

相关文章:

python - python中的默认舍入模式,以及如何将其指定为另一个舍入模式?

c - 如何在C中生成随机 float

XML XSD 十进制分数

perl - 如何修复此 Perl 代码,使 1.1 + 2.2 == 3.3?

python - 十进制转二进制,如何得到8位二进制?

c - 一个基本的 DHCP 客户端

c++ - ABI 兼容性 header /库交叉检查

c++ - 我有一个浮点溢出问题

c - 你如何为c中的数组中的元素赋值?

c - 通用动态数组未正确更新属性