Reputation: 1389
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
Upvotes: 1
Views: 142
Reputation: 57168
When you declare a local variable (like float weight = ...
) it's only visible within the inner-most curly-brace enclosed block. So,
if (...)
{
float weight = ...;
// weight is visible here
}
// weight is not visible here
You should move float weight;
to before the if; something like this:
//Put weight value into a float
float weight;
if (btnKG.selected)
{
weight = ([valWeight.text floatValue]);
}
else
{
weight = ([valWeight.text floatValue]/2.20462);
}
//calculate
float bmr = weight * age;
(EDIT: And incorporated other fix from Anoop)
Upvotes: 1
Reputation: 46543
(btnKG.selected = YES)
is incorrect use (btnKG.selected == YES)
=
is used for assingment.
==
is for comparing.
In your code you are mistakenly assigning the value YES to btnKG.Selected, that is why you are not getting expected result.
Also,
float weight
is local to the block { and }. And you are trying to use it later in calculation. Declare the variable weight out side of { & } inside the method, so that you can use it withing he current method.
Upvotes: 1