Reputation: 1487
I am using a For loop to cycle through variables in an array that contain percentages. For each value I run through an equation to give me an average of all the percentages. The only problem is that I am unsure how to change the variable types to accommodate decimals whilst also work in with my equation.
// Calculate average of all percentages for specific exercise
long totalNumber = 0;
int temp;
long numberOfObjects = [iterationArray count];
for (NSArray *object in iterationArray) {
temp = [(NSNumber *)[object objectAtIndex:4] intValue]/100;
totalNumber = totalNumber + temp;
}
exercisePercentage = (totalNumber/numberOfObjects)*100;
return exercisePercentage;
I know that temp
is the variable that needs to be a decimal. I was considering using an NSDecimalNumber
but didn't know how to fit in with the rest of the code to return a long
value.
I've tried with making temp a double
or float
but both return 0 on the line temp = [(NSNumber *)[object objectAtIndex:4] intValue]/100;
despite the fact that [(NSNumber *)[object objectAtIndex:4] intValue]
is 80.
Upvotes: 1
Views: 359
Reputation: 2902
Division of int with int always returns int, so you need to convert one value into float or double, something like this:
// Calculate average of all percentages for specific exercise
double totalNumber = 0.0;
double temp;
long numberOfObjects = [iterationArray count];
for (NSArray *object in iterationArray) {
temp = [(NSNumber *)[object objectAtIndex:4] intValue]/100.0;
totalNumber = totalNumber + temp;
}
exercisePercentage = (totalNumber/numberOfObjects)*100.0;
return exercisePercentage;
See it's 100.0, now it should work.
Upvotes: 6
Reputation: 278
Please change the type of temp form int to float or double.
double temp;
float temp;
Upvotes: 0