0

I'm trying to calculate an average where i am getting the value from a textfield and multiplying it by the value of a label.

int grade1 = [[self.Cw1Grade text]intValue];
    int grade1weight = self.weight1.text.intValue;

    int a1grade = grade1 / 100; 
    int a1total = a1grade * grade1weight;
    NSString *grade1total = [NSString stringWithFormat:@"%d", a1total];
    [self.averageLabel setText:grade1total];

help appreciated thanks for your time

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • 1
    This is a standard newbie mistake. When you do arithmetic with integers you get an integer result, truncated downward. So dividing 96 by 100, eg, will give you zero. Use floating point. – Hot Licks May 17 '13 at 19:46
  • 1
    Objective-C is C. Learn C. Oh, and please do a search before you post. – matt May 17 '13 at 19:47
  • See also [Getting a float value from integers](http://stackoverflow.com/q/762953) – jscs May 17 '13 at 19:52

1 Answers1

0

You can't divide integers like that. Or well, you can, but you won't get the result you expect, because integer divisions return integers (result will be rounded down to the next whole number)

Try this:

float a1grade = (float)grade1 / 100;

or

float a1grade = grade1 / 100.0;

If at least one of the operands is a float, you'll have a floating point division. But of course you have to store the result in a float variable in that case.

Also don't forget, that the string format specifier for floats is %f, not %d.

DrummerB
  • 39,814
  • 12
  • 105
  • 142