【发布时间】:2015-10-09 12:04:21
【问题描述】:
我的老师指定了一个程序来同时使用if-else 语句和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 语句的最佳方法,即使它根本没有有必要吗?
【问题讨论】:
-
你不能使用双打开关。
-
无关:英寸到米的换算为 0.0254 m/in。此外,很高兴在您的代码中看到命名的转换因子。我无法告诉你我在遗留代码中遇到了多少“神奇数字”,我无法弄清楚数字到底意味着什么。
-
“这对你来说可能没有意义,但有时你将不得不编写一个没有意义的程序。” - 告诉一个奇怪的事情学生。
-
@ChristianHackl 是的。我相信它,因为她不知道自己在说什么。
-
@nocomprende,我强烈反对。在研究问题集时,解决方案似乎不能很好地转换为像 C++ 这样的语言,因为您必须考虑 C++ 语言模拟了一个非常低级的机器:指针和位类型等等。不过,用函数式语言编写的解决方案将非常类似于您的问题集的数学模型。
标签: c++ switch-statement