开发者

Percentage Calculation always returns 0

开发者 https://www.devze.com 2023-01-15 07:04 出处:网络
I am trying to calculate the percentage of something. It\'s simple maths. Here is the code开发者_JAVA百科.

I am trying to calculate the percentage of something. It's simple maths. Here is the code开发者_JAVA百科.

float percentComplete = 0;
if (todaysCollection>0) {
    percentComplete = ((float)todaysCollection/(float)totalCollectionAvailable)*100;
}

Here the value of todaysCollection is 1751 and totalCollectionAvailable is 4000. Both are int. But percentComplete always shows 0. Why is this happening? Can any one Help me out. I'm new to Objective C.


But percentComplete always shows 0

How are you displaying percentComplete? Bear in mind it's a float - if you interpret it as an int without casting it you'll get the wrong output. For example, this:

int x = 1750;
int y = 4000;
float result = 0;
if ( x > 0 ) {
    result = ((float)x/(float)y)*100;
}
NSLog(@"[SW] %0.1f", result);   // interpret as a float - correct
NSLog(@"[SW] %i", result);      // interpret as an int without casting - WRONG!
NSLog(@"[SW] %i", (int)result); // interpret as an int with casting - correct

Outputs this:

2010-09-04 09:41:14.966 Test[6619:207] [SW] 43.8
2010-09-04 09:41:14.967 Test[6619:207] [SW] 0
2010-09-04 09:41:14.967 Test[6619:207] [SW] 43

Bear in mind that casting a floating point value to an integer type just discards the stuff after the decimal point - so in my example 43.8 renders as 43. To round the floating point value to the nearest integer use one of the rounding functions from math.h, e.g.:

#import <math.h>

... rest of code here

NSLog(@"[SW] %i", (int)round(result)); // now prints 44


Maybe try with *(float)100, sometimes that is the problem ;)


I think that your value for todaysCollection and totalCollectionAvailable is wrong. Double check for that.

Put the NSLog(@"%d", todaysCollection) right before the if statement

0

精彩评论

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