0
我一直認爲當浮點數被截斷爲整數時,它總是成爲比浮點數小的最大數。但是,當float在-0.5和0之間時,它將轉換爲0而不是-1!爲什麼是這樣?這是語言特定的嗎?我在objC看到這個。當將浮點數轉換爲int時,爲什麼數字> -1和<-0.5變爲-1,且數字> = -0.5且<0變爲0?
我一直認爲當浮點數被截斷爲整數時,它總是成爲比浮點數小的最大數。但是,當float在-0.5和0之間時,它將轉換爲0而不是-1!爲什麼是這樣?這是語言特定的嗎?我在objC看到這個。當將浮點數轉換爲int時,爲什麼數字> -1和<-0.5變爲-1,且數字> = -0.5且<0變爲0?
嗯,簡單的答案是,你的理解實際上是正確的:
0比-1的數量更多。
更長或更詳細的答案取決於如何將浮點數轉換爲整數。如果你想爲「0.5」浮點數而不是「0」,你可能需要編寫你自己的實現方案,將負數從浮點數中除去,將其向上或向下取整爲一個整數,然後添加(或相乘。-1,要準確)的負號返回到它
這裏有一些代碼我寫的演示中實現的差異:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
float floatNumber = -1.0f;
for(NSInteger index = 0; index < 20; index++)
{
NSLog(@"floatNumber is %4.2f and integer is %d %d", floatNumber, (int) floatNumber, (int)roundf(floatNumber));
floatNumber+=0.1f;
}
}
return 0;
}
在Xcode中,結果出來的:
floatNumber is -1.00 and integer is -1 -1
floatNumber is -0.90 and integer is 0 -1
floatNumber is -0.80 and integer is 0 -1
floatNumber is -0.70 and integer is 0 -1
floatNumber is -0.60 and integer is 0 -1
floatNumber is -0.50 and integer is 0 0
floatNumber is -0.40 and integer is 0 0
floatNumber is -0.30 and integer is 0 0
floatNumber is -0.20 and integer is 0 0
floatNumber is -0.10 and integer is 0 0
floatNumber is 0.00 and integer is 0 0
floatNumber is 0.10 and integer is 0 0
floatNumber is 0.20 and integer is 0 0
floatNumber is 0.30 and integer is 0 0
floatNumber is 0.40 and integer is 0 0
floatNumber is 0.50 and integer is 0 1
floatNumber is 0.60 and integer is 0 1
floatNumber is 0.70 and integer is 0 1
floatNumber is 0.80 and integer is 0 1
floatNumber is 0.90 and integer is 0 1
在C中(並因此在objC)* truncates *中將一個float轉換爲int,這意味着(-1,1)中的任何值都會生成一個零結果。這不是你正在報告的內容,所以還有其他事情在發生。如果您發佈了一些示例代碼,則幫助您會更容易。 – 2013-03-04 12:14:34