c++ - BMI计算器C代码

标签 c++ c if-statement math indexing

我正在尝试编写一个简单的 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;
}

关于c++ - BMI计算器C代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359917/

相关文章:

c++ - 如何计算 ICMP 数据包的往返时间

javascript - Javascript 中更短的 if 语句

Swift If 程序

c++ - extern "C"dllexport 产生奇怪的名字

c++ - Armadillo 要求的尺寸太大

c - 将指向结构体的指针数组传递给函数

c - 将第一个数组索引放在数组末尾

sql-server - 如何在Azure数据工厂上使用查询If Else条件?

c++ - 为什么调用纯虚拟链接器错误而不是编译错误?

c++ - 如何一直运行固定数量的线程