i want to make a switch statementt that uses < or >. it is for a simple program that takes a grade out of 100 and assigns a letter grade. how can i do this? do i need to stick to a whole bunch of if statements, or can this be done?
Printable View
i want to make a switch statementt that uses < or >. it is for a simple program that takes a grade out of 100 and assigns a letter grade. how can i do this? do i need to stick to a whole bunch of if statements, or can this be done?
While you could try using fall-through or goto's, it'll still be a lengthy switch.
Why not KISS with a pure (?) conditional operator?
HTH.Code:int score = 80;
string Ltr_Grade = score > 92 ? "A":
score > 80 ? "B":
score > 70 ? "C":
score > 62 ? "D": "F";
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );
hmmm... the only c# i know is from a high school course i'm taking. i have never seen this operator before. what does it do/how does it work?Quote:
Originally posted by Mongo
While you could try using fall-through or goto's, it'll still be a lengthy switch.
Why not KISS with a pure (?) conditional operator?
HTH.Code:int score = 80;
string Ltr_Grade = score > 92 ? "A":
score > 80 ? "B":
score > 70 ? "C":
score > 62 ? "D": "F";
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );
cond ? expr1 : expr2
If cond is true, the result is expr1. Else it's expr2.
However nesting them like Mongo did makes for terribly unreadable code.
You can only have constants in switch cases. You should use if...else if...else chains for places where you need expressions.
I like Mongo's code even though it's tough on the brain. I've not seen that particular way of using of ?: before.
It's a bugger to read though like Cornedbee said.
Would that code be faster / slower than the equivalent if() statements?
it looks a bit more obvious like this...
...but not muchCode:int score = 80;
string Ltr_Grade =
score > 92 ? "A":
score > 80 ? "B":
score > 70 ? "C":
score > 62 ? "D":
/*default*/ "F";
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );
Or maybe...
Code:int score = 80;
string Ltr_Grade = (score > 92 ? "A": (score > 80 ? "B": (score > 70 ? "C": (score > 62 ? "D": /*default*/ "F"))));
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );
Whether if or ? is faster depends solely on the compiler.