[英]iOS Objective C Programming Xcode using if statements
因此,我嘗試在應用程序中使用if語句來計算人的身體質量指數(BMI)。 我需要用戶能夠輸入重量和高度的公制或英制單位,並且我真的很希望能夠使用戶甚至輸入公制重量和英制高度。 我認為使用if語句將是最佳選擇,而我的代碼如下。 目前,我在if語句上有警告,它只是忽略它們。 非常感謝任何幫助。
- (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]];
}
if-else塊重新聲明了堆棧變量height
和mass
,因此if-else塊之后的代碼將看不到條件結果。 改變這種方式...
// ...
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;
}
順便說一句,可以使這兩個語句更加簡潔:
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.