Math with mixed variable data types
I am calculating a percent complete with variables of mixed data types.
int incompleteCritical = 12;
int total = 24;
float progress = 0;
NSLog(@"Incomplete Total: %d", incompleteCritical);
NS开发者_StackOverflow中文版Log(@"Total Total: %d", total);
if (total > 0) {
progress = ((float)incompleteCritical/(float)total)*100;
NSLog(@"Progress: %d", progress);
}
The console output is as follows:
2011-01-11 10:02:59.993 [18570:207] Incomplete Total: 12
2011-01-11 10:02:59.993 [18570:207] Total Total: 24
2011-01-11 10:02:59.994 [18570:207] Progress: 0
Why is Progress not returning "50"?
You're using the wrong format string in your NSLog
statement. %d
is used for integers. You need to use %f
when you log floating point numbers. (There are extra parameters to use to limit the number of decimal places, etc.)
精彩评论