Range checks using a switch statement

后端 未结 7 1295
陌清茗
陌清茗 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:54

    Unless you have an absolutely ghastly compiler extension, you can't switch on a range in C++.

    But you could use a switch elegantly if you create a std::vector of the BMI ranges:

    std::vector v = {18.5, 25.0 /*etc*/}

    Then use std::lower_bound along with std::distance to get the position of a given BMI in the above ranges. This is the quantity that you switch on.

    You could then go one stage further and define a std::vector of the output messages. Then you need neither a switch nor an if block! All the selection logic is delegated to std::lower_bound.

    I deliberately haven't given you the full code: I trust these hints are sufficient.

提交回复
热议问题