Chapter 1 Challenge. Yes, Already Hit a Wall ;)

I posted this in another section but thought it might be better to post it here. Sorry for the repeat.

I’m 43 years old and desperately want to learn Objective C. I have zero experience but have already run into a problem on my very first challenge.

I really need help understanding the type ‘double.’ There’s a brief explanation about what it is in the chapter but no real examples. So when I try to do the challenge, the syntax is correct, but the ‘double’ part never shows up in the ‘print’ function. How can this be resolved? And remember, no computer lingo. I’m really illiterate except for a few things here and there. Also, is there anyway to attach screenshots so I can show you what I’m talking about? Thanks.

Steven

In Objective-C programs, type double (and its relatives) is used to encode (represent) real numbers, numbers with fractional parts.

For an example, take a look at the following program and its output. The program defines two numbers and prints them by using the printf function.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    
    // A real number
    double real_v = 2.34567;

    // An integer number
    long int_v  = 2.34567;

    // Print both
    printf ("real_v = %f int_v = %ld\n", real_v, int_v);
    
    // Print only the real number, with different format directives
    printf ("%.0f\n", real_v);
    printf ("%.1f\n", real_v);
    printf ("%.2f\n", real_v);
    printf ("%.3f\n", real_v);
    printf ("%.5f\n", real_v);

    return 0;
}

The output:

real_PI = 2.345670 int_PI = 2
2
2.3
2.35
2.346
2.34567

Now do the following exercise.

Replace the first printf statement:

    // Print both
    printf ("real_v = %f int_v = %ld\n", real_v, int_v);

With:

    // Print both
    printf ("%f %ld\n", real_v, int_v);

And compile and run the program. What difference can you see in the output? What can you say about “real_v = %f int_v = %ld\n” and “%f %ld\n”?

You can learn more about the printf function by reading its user manual, which can be accessed in Xcode or from the command line.

To display the user manual from the command line:

  1. Open the Terminal Application; and
  2. Enter the command: man 3 printf.

[Become a competent programmer faster than you can imagine: pretty-function.org]