0

Possible Duplicate:
How do I select a range of values in a switch statement?
c++ cannot appear in a constant-expression|

What I'm trying to do is generate a random number, and, depending on the value of the number, write out "Common", "Rare", or "Very Rare". Can somebody help me?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    int a;
    srand(time(0));
    a = 1 + (rand()%10);

    switch (a)
    {
        case (a >= 0 && a <= 5):
        cout << "Common";
            break;

        case (a >= 6 && a <= 8):
        cout << "Rare";
            break;

        case (a >= 9 && a <= 10):
        cout << "Very rare";
            break;

        default:
            break;
    }

    return 0;
}
Community
  • 1
  • 1
AethariA
  • 19
  • 2

2 Answers2

4

You can't use comparison operators in a switch case. Try this:

 switch (a)
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        cout << "Common";
            break;

        case 6:
        case 7:
        case 8:
        cout << "Rare";
            break;

        case 9:
        case 10:
        cout << "Very rare";
            break;

        default:
            break;
    }
billjamesdev
  • 14,554
  • 6
  • 53
  • 76
  • Also, the switch statement ends with a semicolon. – wjmolina Dec 04 '12 at 04:48
  • Hmm, I'm a Java guy, so I'll believe it, but I didn't think so. – billjamesdev Dec 04 '12 at 04:49
  • It's a = 1 + (rand()%10); So it'll add 1, making the possible range be 1-10. And yeah, I figured that was the error. Thank you very much, I didn't know I could make more than one case have the same output in that way. Thanks again! :D – AethariA Dec 04 '12 at 04:49
  • 1
    @Josué Molina: Not necessarily. In C++, classes require semicolons, switch statements don't. – In silico Dec 04 '12 at 04:50
  • Alternately, the original question could have gone with chained else-if's. – MPelletier Dec 04 '12 at 04:51
  • Wow, I just tested it and it works; switch statements can end and not end with a semicolon. o.o I guess we learn something new every day. – wjmolina Dec 04 '12 at 04:54
2

If you want to check ranges I recommend you to use the if statement to avoid using a list of all possible values:

if (a >= 0 && a <= 5)
    cout << "Common";
else if (a >= 6 && a <= 8)
    cout << "Rare";
else if (a >= 9 && a <= 10)
    cout << "Very rare";
axelbrz
  • 783
  • 1
  • 7
  • 16