所有这些
else if (16 < bmi <= 18.5) {
错了。他们不做你想让他们做的事。要达到所需的结果,请使用
else if (16 < bmi && bmi <= 18.5) {
原因是,你的表达式被评估为
else if ((16 < bmi) <= 18.5) {
where (16 < bmi)
评估为true
or false
这又等于1
or 0
,然后与第二个常数进行比较。之所以这样评估,是因为比较运算符是左结合 http://en.cppreference.com/w/cpp/language/operator_precedence,因此从左到右进行评估。
Edit 2
强制性 SO 链接:(4 > y > 1) 在 C++ 中是有效的语句吗?如果是的话你如何评价? https://stackoverflow.com/questions/8889522/is-4-y-1-a-valid-statement-in-c-how-do-you-evaluate-it-if-so
Edit
我怀疑这个,但不知道公式。现在@MOehm 已经证实了这一点(维基百科似乎也证实了这一点):
bmi = (weight/(height/100)*(height/100));
应该成为
bmi = (weight/((height/100)*(height/100)));
这里的原因几乎相同:C++ 中的运算符优先级和表达式求值规则。 OP,注意这些方面并在适当的地方加上括号!
Edit 3以下是我如何使用 STL 来实现这一点(这种方法的好处是可以清楚地表达算法背后的想法,而不会将其隐藏在实现细节之下):
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <limits>
#include <algorithm>
int main()
{
std::vector<std::pair<float, std::string> > bmi_table = {
{ 16, "Severely Underweight" },
{ 18.5, "Underweight" },
{ 25, "Healthy" },
{ 30, "Overweight" },
{ std::numeric_limits<float>::max(), "Severely Overweight" }
};
float height, weight;
std::cin >> height >> weight;
const float bmi = (weight/((height/100.f)*(height/100.f)));
const auto idx =
std::find_if(bmi_table.begin(),
bmi_table.end(),
[&](decltype(bmi_table)::value_type& p) -> bool { return p.first > bmi; });
std::cout << idx->second << '\n';
return 0;
}