Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
我正在尝试编写一个简单的BMI计算器,但是由于某些原因,当我尝试将175设置为身高(该公式使1.75)并且将70设置为质量时,它应该得到22.8,在健康范围内,但是它使我体重不足。我知道这可能是一个简单的错误,但我看不到。

float main(void) {

    float height;
    printf("Enter your height in cm:\n");
    scanf("%f",&height);

    float weight;
    printf("Enter your weight in kg:\n");
    scanf("%f",&weight);

    float bmi;
    bmi = (weight/(height/100)*(height/100));

    if (bmi <= 16) {
        printf("Severely Underweight\n");
    }
    else if (16 < bmi <= 18.5) {
        printf("Underweight\n");
    }
    else if (18.5 < bmi <= 25) {
        printf("Healthy\n");
    }
    else if (25 < bmi <= 30) {
        printf("Overweight\n");
    }
    else {
        printf("Severely Overweight\n");
    }
}

最佳答案

所有这些

else if (16 < bmi <= 18.5) {


错了。他们没有按照你的意思去做。为了达到预期的效果,请使用

else if (16 < bmi && bmi <= 18.5) {


原因是,您的表达式被评估为

else if ((16 < bmi) <= 18.5) {


其中,(16 < bmi)的计算结果为truefalse,而后者又等于10,然后与第二个常量进行比较。之所以这样求值,是因为比较运算符是left-associative,因此从左到右求值。

编辑2

必填SO链接:Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?

编辑

我怀疑这个,但不知道公式。现在,@ MOehm已经确认了这一点(维基百科似乎也对此进行了确认):

bmi = (weight/(height/100)*(height/100));


应该成为

bmi = (weight/((height/100)*(height/100)));


原因大致相同:C ++中的运算符优先级和表达式求值规则。 OP,请注意这些方面,并在适当的地方加上括号!

编辑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;
}

10-07 19:20
查看更多