Range checks using a switch statement

后端 未结 7 1271
陌清茗
陌清茗 2020-12-23 02:15

My teacher has assigned a program to use both if-else statements and switch statements, so we understand how to implement both. The program asked u

7条回答
  •  萌比男神i
    2020-12-23 03:07

    You can do something like:

    switch ((round)BMI)
    {
        case 1: case 2: case 3: .... case 15: case 16: case 17: cout<< "You are underweight " << endl; break;
        case 18: ... case 24: cout << "You are normal" << endl; break;
        case 25: ... case 29: cout << "You are overweight" << endl; break;
        case 30: ... case 34: cout << "You are obese" << endl; break;
        default: cout << "You are gravely overweight" << endl;
    }
    

    Also I couldn't help but notice this that since you are using if-else you can avoid the first condition in else-if statements like:

    if (BMI < 18.5)
    {
        cout << "You are underweight " << endl;
    }
    else if (BMI < 25.0)
    {
        cout << "You are normal" << endl;
    }
    else if (BMI < 30.0)
    {
        cout << "You are overweight" << endl;
    }
    else if(BMI < 35)
    {
        cout << "You are obese" << endl;
    }
    else
    {
        cout << "You are gravely overweight" << endl;
    }
    

    Apart from this, both of your implementations look good.

提交回复
热议问题