Search code examples
objective-cvariablesdoublenslogarithmetic-expressions

Interesting output using variables with NSLog() in objective-c


The following code:

int N = 100;
double total_time = 100;
double dt = total_time/N;
NSLog(@"Answer: %d", dt);

gives an interesting output: 5766 instead of 1.

Only in the case of adding

NSLog(@"Answer: %f", dt);

outputs the right answer. However, I would like to output "double" value instead of "float". What's wrong with my expectations and syntax?


Solution

  • %d means "decimal representation of int", not "double".

    You always output a double value using %f, because NSLog() has an open arg list. In such a case, all floating point numbers are passed as doubles. So you should read %f as "floating point number" not float.