• c++ "switch" help
    7 replies, posted
how do i convert this into a switch, i did this code then my teacher said use a switch statement? if (score > 90) cout << 'A'; else if (score > 80) cout << 'B'; else if (score >70) cout << 'C'; else if (score > 60) cout << 'D'; else cout << 'F';
Maybe I'm wrong because I'm new to C++, but wouldn't a switch statement be much less useful in this case versus using an if/else-if structure? Switches can only compare an expression against a constant, meaning you'd have to do like case 1: case 2: case 3: and so on for every single number.
haha yeah maybe but thats just what she told me to do. i am looking off shit on another website and i think i might understand how to do it for the most part [editline]13th December 2010[/editline] #include <iostream> using namespace std; int main(void) { char grade; cout << "Enter your grade: "; cin >> grade; switch (grade) { case 'A': cout << "Your average must be between 90 - 100" << endl; break; case 'B': cout << "Your average must be between 80 - 89" << endl; break; case 'C': cout << "Your average must be between 70 - 79" << endl; break; case 'D': cout << "Your average must be between 60 - 69" << endl; break; default: cout << "Your average must be below 60" << endl; } return 0; } i have that but she wants it to be the opposite way like if i enter a number it will give me a letter grade
[QUOTE=ttrexler99;26668444]i have that but she wants it to be the opposite way like if i enter a number it will give me a letter grade[/QUOTE] Show her that e.g. case > 90 doesn't work.
[QUOTE=ttrexler99;26668444]i have that but she wants it to be the opposite way like if i enter a number it will give me a letter grade[/QUOTE] You can't do that with a switch statement. :/ Not really sure what you can do here except tell her that.
alright thanks
:downs: MUCH MORE EFFICIENT THAN USING IF/ELSE-IF. [code] case 105: case 104: case 103: case 102: case 101: case 100: case 99: case 98: case 97: case 96: case 95: case 94: case 93: case 92: case 91: case 90: cout << "YOU GOT AN A GOOD JOB." break; case 89: case 88: case 87: case 86: case 85: case 84: case 83: case 82: case 81: case 80: cout << "YOU GOT A B GOOD JOB." break; case 79: case 78: case 77: case 76: case 75: case 74: case 73: case 72: case 71: case 70: cout << "YOU GOT A C..." break; case 69: case 68: case 67: case 66: case 65: case 64: case 63: case 62: case 61: case 60: cout << "WHY YOU GOT D?" break; default: cout << "YOU OBVIOUSLY SUCK BECAUSE YOU GOT AN F." break; [/code]
That is possible too.... [editline]13th December 2010[/editline] But it's a horrible way to do that kind of thing, just stick with ifs.
Sorry, you need to Log In to post a reply to this thread.