Reputation: 3105
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?
Upvotes: 0
Views: 204
Reputation: 4895
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:
.
Upvotes: 1
Reputation: 146603
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);
Upvotes: 2
Reputation: 74702
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.
Upvotes: 8