开发者

double problem in xcode or me doing something wrong

I would guess it's the simplest thing but it's really confusing me. I'm sure I've successfully used doubles before but now I'm having trouble.

I just made a new 'test' project to see if I can get it working, but all I'm trying to do is set开发者_运维问答 a double value.

So in the View Controller's viewDidLoad i've typed:

double z = 2938.09;
NSLog(@"z = %d", z);

I would expect it to output 'z = 2938.09' but instead I get 'z = 343597384'

double z = 3.4 returns z = 858993459

Also most integer values report back as z = 0, however not always (sometimes another strange number as above is spewed out)

Am I missing something here or it something strange going on??

Even tried stuff like

NSString *newString = [[NSString alloc] initWithString:@"3.4"];
double z = [newString.text doubleValue];
NSLog(@"z = %d", z);
[newString release];

but still get the crazy z = 858993459 :(


For printing the Double value use %f instead of %d.

NSlog format specifiers

%@ Object

%d, %i signed int

%u unsigned

%f float/double

%x, %X hexadecimal int

%o octal

%zu size_t

%p pointer

%e float/double (in scientific notation)

%g float/double (as %f or %e, depending on value)

%s C string (bytes)

%S C string (unichar)

%.*s Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)

%c character

%C unichar

%lld long long

%llu unsigned long long

%Lf long double


Double is a double precision float, and so, to print you should use the same way used to print floats:

NSString *newString = [[NSString alloc] initWithString:@"3.4"];
double z = [newString.text doubleValue];
NSLog(@"z = %f", z);
[newString release];

%d is used to print signed int.

Have a look at this link with the format specifiers for NSLog: http://www.cocoadev.com/index.pl?NSLog

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜