views:

72

answers:

3

I have a calculation which isn't working and I cannot work out why!

int numHoursInWeek;
int numDays;
int averageSalary;

int total_seconds_in_year = ((numHoursInWeek * 60 * 60) * numDays);

NSLog(@"average sal in pence=%i", (averageSalary * 100));
NSLog(@"num seconds in year=%i", total_seconds_in_year);
NSLog(@"cost per second=%i", ((averageSalary * 100) / total_seconds_in_year));

int cost_per_person_per_second = ((averageSalary*100) / total_seconds_in_year);

costPerSecond = (cost_per_person_per_second * numPeople);
lblCostPerPerson.text = [NSString stringWithFormat:@"%.2f",cost_per_person_per_second];

the above returns the following in NSLog

average sal in pence=3400000
num seconds in year=31968000
cost per second=-1.991753

I know everything else is being set correctly (numDays, averageSalary for example). When I do the calc manually, I get 0.1063. So that should show on my label?? (cost per person per second).

any ideas? should I be using floats instead of ints for the variables?

+8  A: 

When you do integer division, numbers are truncated, so:

6 / 4
>>> 1

Change your data type to float or double, and write all of your numbers as "100.0" for example - otherwise it will be treated as an int.

Paul Betts
+1: Misconceptions about integer v. floating point operations is a leading cause of bugs in many programs - particularly since they can oftenbe subtle to diagnose and work under certain conditions and inputs but not others. All developers should familiar themselves with how arithmetic operations actually work in the language they use. It can save a lot of grief.
LBushkin
thanks guys - I'll change them all and use as instructed. Will post back when confirmed!
Matt Facer
+2  A: 

Looking at

total_seconds_in_year = ((numHoursInWeek * 60 * 60) * numDays);

Shouldn't that be

total_seconds_in_year = ((numHoursInWeek * 60 * 60) * numWeeks);

or

 total_seconds_in_year = ((numHoursInDay * 60 * 60) * numDays);
Charles Bretana
yes you are correct - well spotted, thanks!!
Matt Facer
+1  A: 

When you use "%f", make sure that the argument is a float or double, not an integer. GCC will warn you about this for printf, but for some reason it can't do this for stringWithFormat:.

Derek Ledbetter