我尝试拆分任意数量的两位数字,并在两个不同的变量中得到结果。我遇到了一个特定数字的问题: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/