After @property change, why am I getting result 'inf'


#1

After replacing the accessor declaration and definition with @property and @synthesize, I am getting an output of ‘inf’ for the bmi variable. Strangely, when I write the whole formula in the NSLog function, I get the right answer.

Can someone please explain?

Here is main.m (I have added to the contents of NSLog to make sure the formula works)

[code]#import <Foundation/Foundation.h>
#import “Person.h”

int main(int argc, const char * argv[])
{

@autoreleasepool {
    
    // Create an instance of Person
    Person *person = [[Person alloc] init];
    
    // Give the instance variables interesting values
    [person setWeightInKilos:96];
    [person setHeightInMeters:1.8];
    
    // Call the bodyMassIndex method
    float bmi = [person bodyMassIndex];
    NSLog(@"person (%dkg, %.1fm) has a BMI of %.1f %f",[person weightInKilos], [person heightInMeters], [person weightInKilos] / ([person heightInMeters] * [person heightInMeters]), bmi);
    
}
return 0;

}
[/code]

And here is the output I am receiving:

Person.h:

[code]#import <Foundation/Foundation.h>

// The class Person inherits all the instance variables and methods defined by the class NSObject

@interface Person : NSObject
{
// It has two instance variables
float heightInMetres;
int weightInKilos;
}

@property float heightInMeters;
@property int weightInKilos;

// This method calculates the Body Mass Index

  • (float) bodyMassIndex;

@end[/code]

Person.m:

#import "Person.h"

@implementation Person

@synthesize heightInMeters, weightInKilos;

- (float) bodyMassIndex
{
    return weightInKilos / (heightInMetres * heightInMetres);
}

@end

#2

Are those direct cut and pastes? Because in some places you have heightInMeters and in others you have heightInMetres. You might be getting a divide by zero.


#3

NOTE TO SELF: Attention to detail! School boy error.

Thanks…although I would of thought Xcode would pick upon it by warning me?


#4

I think the reason why it didn’t generate a warning is that you have one spelling synthesized and one spelling declared explicitly, so both variables actually existed, and used in different places. Then when you set one but divided by the other one, the divide by zero happened and you got the infinity token back as a result.