Range checks using a switch statement

后端 未结 7 1294
陌清茗
陌清茗 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条回答
  •  太阳男子
    2020-12-23 02:56

    You could calculate your case labels dynamically from an array/vector instead of hardcoding an if/else expression:

    //#include "stdafx.h"
    #include 
    
    using namespace std;
    
    
    inline int seg(double d){ //calculate segment for a BMI of d
      constexpr double segs[] = { 18.5, 25, 30, 35 };
      constexpr int n = sizeof(segs)/sizeof(double);
      int r; for(r=0; r> height >> weight;
    
      weightKilo = weight*KILOGRAMS_PER_POUND;
      heightMeters = height*METERS_PER_INCH;
      BMI = weightKilo / (heightMeters*heightMeters);
    
    
    
      switch (seg(BMI)) {
        case 0: cout << "You are underweight" << endl; break;
        case 1: cout << "You are a normal weight " << endl; break;
        case 2: cout << "You are overweight" << endl; break;
        case 3: cout << "You are obese" << endl; break;
        case 4: cout << "You are gravely overweight" << endl; break;
      }
    
    }
    

    (You could even make the seg functions constexpr if your really wanted to).

提交回复
热议问题