[英]iOS Objective C Programming Xcode using if statements
So I am trying to use if statements in an app to calculate a persons body mass index (BMI). 因此,我尝试在应用程序中使用if语句来计算人的身体质量指数(BMI)。 I needs the user to be able to input either metric or imperial units for weight and height and I would really like to be able to have the user even input metric weight for example, and imperial height. 我需要用户能够输入重量和高度的公制或英制单位,并且我真的很希望能够使用户甚至输入公制重量和英制高度。 I thought using an if statement would be best and my code is below. 我认为使用if语句将是最佳选择,而我的代码如下。 Currently I have warnings on the if statements and it just ignores them. 目前,我在if语句上有警告,它只是忽略它们。 Many thanks to any help. 非常感谢任何帮助。
- (IBAction)calculateProcess:(id)sender {
float cm = [_cmHeight.text floatValue];
float feet = [_feetHeight.text floatValue];
float inches = [_inchesHeight.text floatValue];
float kg = [_kgWeight.text floatValue];
float stone = [_stoneWeight.text floatValue];
float pound = [_poundWeight.text floatValue];
float height;
float mass;
if (cm == 0){
float height = 0.3048*feet + 0.0254*inches;
} else {
float height = cm/100;
}
if (kg == 0){
float mass = (6.35029*stone) + (0.453592*pound);
} else {
float mass = cm/100;
}
float bmi = mass/(height*height);
[_resultLabel setText:[NSString stringWithFormat:@"%.2f", bmi]];
}
The if-else blocks redeclare the stack variables height
and mass
, so the code after the if-else blocks won't see the conditional results. if-else块重新声明了堆栈变量height
和mass
,因此if-else块之后的代码将看不到条件结果。 Change this way ... 改变这种方式...
// ...
float height;
float mass;
if (cm == 0){
// see - no float type
height = 0.3048*feet + 0.0254*inches;
} else {
height = cm/100;
}
if (kg == 0){
mass = (6.35029*stone) + (0.453592*pound);
} else {
mass = cm/100;
}
As an aside, both statements can be made more concise like this: 顺便说一句,可以使这两个语句更加简洁:
height = (cm == 0)? 0.3048*feet + 0.0254*inches : cm/100;
mass = (kg == 0)? (6.35029*stone) + (0.453592*pound) : cm/100;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.