开发者

Why is float getting rounded off in this Objective C / Cocoa code

I am doing a simple :

float x = 151.185436;
printf("x=%开发者_高级运维f",x);

and the result is

x=151.185440

Whats wrong here? I want to retain and print my original value of 151.185436

Thanks Amarsh


floats just aren't very accurate. Try double. And read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html


A float can only hold 32 bits (4 bytes) of information about your number - it can't just store as many decimal places as you need it to. 151.18544 is as close to your value that the float could represent without running out of bits.

For the precision you want, you need to use a double instead of a float.


Floats are inaccurate, use doubles. Also as you're using Objective C and not straight C it might be better if you use Objective C functions for this:

myNumber = [NSNumber numberWithDouble:151.185436];
NSLog(@"myNumber = %@", myNumber);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜