我的老师布置了一个练习,要求我们使用if-else
语句和switch
语句,以便了解如何实现两者。练习要求我们提示用户输入他们的体重和身高,分别以磅和米为单位。这是我的尝试:
没有使用switch语句
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double height, weight, BMI, heightMeters, weightKilo;
const double KILOGRAMS_PER_POUND = 0.45359237;
const double METERS_PER_INCH = 0.0245;
cout << "Please enter your height (inches) and weight (pounds)" << endl;
cin >> height >> weight;
weightKilo = weight*KILOGRAMS_PER_POUND;
heightMeters = height*METERS_PER_INCH;
BMI = weightKilo / (heightMeters*heightMeters);
if (BMI < 18.5) {
cout << "You are underweight " << endl;
}
else if (BMI >= 18.5 && BMI < 25.0) {
cout << "You are normal" << endl;
}
else if (BMI >= 25.0 && BMI < 30.0) {
cout << "You are overweight" << endl;
}
else if (BMI >= 30.0 && BMI < 35) {
cout << "You are obese" << endl;
}
else {
cout << "You are gravely overweight" << endl;
}
}
随着转变
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double height, weight, heightMeters, weightKilo;
int BMI, q;
const double KILOGRAMS_PER_POUND = 0.45359237;
const double METERS_PER_INCH = 0.0245;
cout << "Please enter your height (inches) and weight (pounds)" << endl;
cin >> height >> weight;
weightKilo = weight*KILOGRAMS_PER_POUND;
heightMeters = height*METERS_PER_INCH;
BMI = weightKilo / (heightMeters*heightMeters);
if (BMI < 18.5) {
q = 1;
}
else if (BMI >= 18.5 && BMI < 25.0) {
q = 2;
}
else if (BMI >= 25.0 && BMI < 30.0) {
q = 3;
}
else if (BMI >= 30.0 && BMI < 35) {
q = 4;
}
else {
q = 5;
}
switch (q) {
case 1: cout << "You are underweight" << endl; break;
case 2: cout << "You are a normal weight " << endl; break;
case 3: cout << "You are overweight" << endl; break;
case 4: cout << "You are obese" << endl; break;
case 5: cout << "You are gravely overweight" << endl; break;
}
}
这是我考虑使用switch语句的方式。有没有方法可以将第一个代码块实现为仅使用switch语句?我几乎确定不能使用范围或双精度数值(18.5)。我给我的老师发了一封电子邮件,他们给了我以下答复:“这可能对你来说毫无意义,但有时你必须编写一个程序,它本身就没有意义。我并不是说你没有合理的问题,如果有人能够弄清楚,那就是你。但是,也许它无法被解决。这就是挑战”。
所以,我想问:是否有一种方法可以只使用switch语句来处理第一个代码块,或者我所做的是在代码中使用switch语句的最佳方式,即使这样做并不必要?