1 2 3 4 5 6 7 8 9 10 11 12
|
switch ((int) grade)
{
case 200:
case 199:
case 198:
...
"A" ...
...
default "D"
}
|
that obviously has both flaws and kinda stinks, and even doing it without the *10 (its only a few entries per value that way) you still have some floating point issues. You may want to take a floor or ceil or round of the thing instead of just (int) casting.
if/then chain is easier to construct for this task.
you could spend some time to make an equation or something that gave the correct grade from a lookup table. This is how I would do it if I cared about performance or wanted to annoy whoever had to read and maintain it.
(grade >= 12) *( 1+ (int)(grade>=15) + (int)(grade>=17.5) );
if that is < 12 you get zero.
if its less than 15 and greater than 12 you get 1
if its greater than 15 and less than 17.5 you get 2
if its greater than 17.5 you get 3.
if you had a table "DCBA" table[0] is D, table[1] is C.... right?
... and I think i overengineered the expression. I think you can just sum the 3 terms and remove the 1. I was originally thinking the default to zero needed that multiply, until after I wrote it and looked at it.
so
(grade >= 12) + (int)(grade>=15) + (int)(grade>=17.5) ;
0,1,2,3 as before, just less weird :P
if not already obvious, you end up with a one-liner
result = table[expression];