-2

I am doing a small calculation but it always returns 0..

    int totalBothTeams = [prefs integerForKey:@"totalTimeBothTeams"];
    int someCalculation = (totalBetween / totalBothTeams) * 100;

    NSLog(@"Time: %i", someCalculation);

Any ideas?

Adam Rush
  • 155
  • 3
  • 16
  • 2
    integer division/truncation. try `(totalBetween * 100 / totalBothTeams)` – Floris Jan 13 '14 at 22:35
  • 1
    You really should have learned this sort of stuff when you learned C, and you should have learned C before diving into Objective-C. – Hot Licks Jan 13 '14 at 22:55

2 Answers2

6

I am assuming that totalBetween is less than totalBothTeams - in which case the division

totalBetween / totalBothTeams

results in the integer value 0

If you are looking for a "percentage" type of answer, you can multiply by 100 before taking the division. You will still get "rounding down". Or you can do the whole thing in double precision and cast at the end:

(totalBetween * 100) / totalBothTeams

or

(totalBetween * 100.0) / totalBothTeams + 0.5
  • the latter will round correctly
Floris
  • 45,857
  • 6
  • 70
  • 122
0

Here is what actually happening:

int someCalculation = (totalBetween / totalBothTeams) * 100;

In this, if totalBothTeams > totalBetween.. and by name it is..

(totalBetween / totalBothTeams) will return 0 as it is integer division.

and 0*any thing =0

so go for (totalBetween * 100 / totalBothTeams);

Prince Agrawal
  • 3,619
  • 3
  • 26
  • 41