0

可能重复:
如何在 switch 语句中选择一系列值?
c++ 不能出现在常量表达式中|

我要做的是生成一个随机数,并根据数字的值写出“常见”、“稀有”或“非常稀有”。有人可以帮助我吗?

#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;
}
4

2 回答 2

4

您不能在 switch case 中使用比较运算符。尝试这个:

 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;
    }
于 2012-12-04T04:46:24.800 回答
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";
于 2012-12-04T04:58:41.927 回答