Ok guys, i’ve got a simple calculation that’s not working.
I’ll give a really basic example of the problem.
I have a KG Button and a Pounds button. If the KG button is selected, float weight is the value in my weight text box. If the Pounds button is select, I divide the number in the weight text box by 2.2 and make it float weight.
I’ve written an if function for this and at the end, I want to multiply weight and age. Age is just whatever number is in the age text box.
-(IBAction)calculate;
{
//put age value into a float
float age = ([valAge.text floatValue]);
//Put weight value into a float
if (btnKG.selected = YES)
{
float weight = ([valWeight.text floatValue]);
}
else
{
float weight = ([valWeight.text floatValue]/2.20462);
}
//calculate
float bmr = weight * age;
}
I get an error on the calculation stage that weight is an undeclared identifier. No problems with age though.
I’m guessing the if function is causing the problem. I’m sure it’s something really silly i’m overlooking.
Can anybody help please?
Thanks
When you declare a local variable (like
float weight = ...) it’s only visible within the inner-most curly-brace enclosed block. So,You should move
float weight;to before the if; something like this:(EDIT: And incorporated other fix from Anoop)