NSLog(@"%d", a) NSLog(@"%g", a); difference between @"%d" and @"%g"
Asked Answered
C

1

7
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSLog(@"Hello, World!");
    float a = 12.3454323;
    NSLog(@"%d", a);
    NSLog(@"%g", a);
    [pool drain];
    return 0;
}

hi, i made very simple program to explain my question: output of this program is:

1st line: some random number (394883904, or 89374e-15 or ...) 2line: 12.3454323

so.. my question: what is @"%d" and what is @"%g").. because, IF a is INTEGER (int a = 156)

then @"%d" gives 156 BUT @"%g" gives 8.32059e-315 or similar :)

i'm doing bluetooth transfer of these values, but this is my problem to send positions what are in integer and then to show it, it is working but i have to check what is what, so, is there any lesson about @"%d" and similar staff? when use @"%d" and when use @"%g".. and are there any other @"%something"? thank you

edit: of course, zero line is hello world! :)

Camus answered 8/3, 2011 at 18:44 Comment(0)
O
14

%d prints out an integer, %g prints out a float or double. If you give %d a float or double, or %g an integer, you will get incorrect results that may or may not be more or less equivalent to what you would get with *(int *)&floatVar or *(double *)&intVar.

The full list of string formatting specifiers is in the documentation.

Olszewski answered 8/3, 2011 at 18:55 Comment(5)
Pretty sure %i is integer and %d is double or floatRna
@ChaseWalden: You're wrong. Check the documentation linked in the answer.Olszewski
%i is for integer and %f is for double or floatBehnken
@Behnken Read the documentation, you are correct but there many ways you can print a double / float.Rampart
%g prints a float but strips trailing zeros.Breathing

© 2022 - 2024 — McMap. All rights reserved.