Quick question, I’m writing a Grade letter program using only switch statements. With if statements I can easily use <, or > to designate a certain range. If the user inputs a number such as 93 I would have to list all the cases from 99-90 which is too redundant. I already wrote the program and it works fine, but I want to get away from bad code. Is there a more reasonable way to write this without listing multiple cases? Hope this makes sense…
Quick question, I’m writing a Grade letter program using only switch statements. With if
Share
You wouldn’t want to use a switch statement to determine where a value falls in a set of ranges.
If you want to generalize a bit, and avoid multiple if/else statements with hard coded conditions, you could create a map. i.e. you are essentially mapping a set of integers to a set of grades.
Below is a simple example that uses a table lookup to map scores to grades. You could also create a closed mathematical formula that maps scores to grades, and just compute the grade directly from the score, instead of looking it up via a table. e.g. f(x) = floor(2*(x-50)/20) would map scores from [0,100] into integer grades in the range [0, 5]