如何在switch语句中使用随机生成的数字?

时间:2015-06-27 15:57:58

标签: c++ random switch-statement ctime

我正在创建一个简单的程序,用于显示我在switch语句中写的句子中的人的行为。我想随机生成1到10之间的数字并在"切换(这个地方)"中使用它。到目前为止,我已经编写了以下代码并坚持到这里..

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int rand_range(int low, int high)
{
  return rand()%(high-low) + low;
}
int main()
{
    srand(time(NULL));
    cout<<"Hi!, this program tells you about your behaviour"<<endl;
    cout<<"press enter to continue";
    cin.get();

    switch(    )
    {
    case 1:
        {
            cout<<"you are rude !";
        }
    case 2:
        {
            cout<<"you are smart";
        }
    case 3:
        {
            cout<<"you try to prove yourself special all the time";
        }
    case 4:
        {
            cout<<"you are good in sarcasm";
        }
    case 5:
        {
            cout<<"you look dumb, but deep inside you are intelligent";
        }
    case 6:
        {
            cout<<"you are always ready for a debate with someone";
        }
    case 7:
        {
            cout<<"you are very lazy";
        }
    case 8:
        {
            cout<<"you are dumber than what you look";
        }
    case 9:
        {
            cout<<"you always try to help others";
        }
    case 10:
        {
            cout<<"you have good decision making capabilities";
        }
    default:
        {
            cout<<"something wrong";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在括号中的switch语句中,您需要rand()。在为随机数生成器播种后,RAND_MAX函数将返回0到RAND_MAX之间的数字。 %是一个很大的数字。

要获取范围内的随机数,标准技巧是使用rand() % 10运算符。 $arr = array(); $arr["one"] = 1; $arr["two"] = 2; $arr["three"] = 3; foreach ($arr as $k => &$v) { $v += 3; } foreach ($arr as $k => $v) { echo("\n".$k." => ".$v); } 返回0到9之间的数字。添加1可获得1到10的范围。