我编写了一个 iPhone 应用程序并遇到了有关 float 和 int 之间类型转换的问题。我用 C 语言重写了代码,无论是在 OS X(控制台和 Xcode)、Linux(控制台)还是 Windows(Visual Studio)下编译,结果总是一样的:
// Calculation of a page index depending on the amount of pages, its x-offset on the view
// and the total width of the view
#include <stdio.h>
int main()
{
int result = 0;
int pagesCnt = 23;
float offsetX = 2142.0f;
float width = 7038.0f;
offsetX = offsetX / width;
offsetX = (float)pagesCnt * offsetX;
result = (int)offsetX;
printf("%f (%d)\n", offsetX, result);
// The console should show "7.000000 (7)" now
// But actually I read "7.000000 (6)"
return 0;
}
当然,我们在这里失去了精度。当使用计算器进行数学计算时,x 结果为 7.00000000000008 而不仅仅是 7.000000。
然而,就我对 C 的理解而言,这应该不是问题,因为 C 旨在将 float 转换为整数时截断 float 的后点位置。在这种情况下,这正是我真正想要的。
当使用 double 而不是 float 时,结果会如预期的那样,但我在这里不需要 double ,它应该没有任何区别。
我这里有什么问题吗?在某些情况下我应该避免使用 (int) 转换为 int 吗?为什么 C 总是递减结果?我是否应该始终使用 double?
非常感谢!
编辑:我表述有误:当然,使用 double 而不是 float 会有所不同。我的意思是,它不应该对 (int) 7.000000f 或 7.00000000000008 产生影响。
编辑 2:多亏了你,我现在明白了我的错误。使用 printf() 而不定义浮点精度是错误的。 (int)ing 6.99... to 6 当然是正确的。所以,以后遇到这种问题我就用double。
最佳答案
当我增加输出的精度时,我从您的程序收到的结果是 6.99999952316284179688 (6)
,因此 6
似乎是正确的。
关于C(C++、Objective-C)从 float 到 int 的类型转换导致 int 递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229920/