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

标签 c++ random switch-statement ctime

我正在制作一个简单的程序,根据我在 switch 语句案例中写的句子显示人的行为。我想随机生成一个 1 到 10 之间的数字,并在“switch(this place)”中使用它。到目前为止,我已经编写了以下代码并卡在这里..

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

最佳答案

在括号中的 switch 语句中,您需要 (rand() % 10) + 1。在您为随机数生成器设置种子后,rand() 函数将返回一个介于 0 和 RAND_MAX 之间的数字。 RAND_MAX 是一个大数。

要获得范围内的随机数,标准技巧是使用 % 运算符。 rand() % 10 返回 0 到 9 之间的数字(含 0 和 9)。加 1 得到 1 到 10 的范围。

关于c++ - 如何在 switch 语句中使用随机生成的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090640/

相关文章:

javascript - 使用 php(?) 在每个服务器日随机增加数值

Java Switch语句困惑

MySQL - 1 id 多行并将多列数据转换为逗号分隔行

php - 将 PHP switch case 与 html 混合的更简洁的方法

c++ - 理解类型特征的架构

c++ - 使用概率在各种选项之间进行选择

c++ - 在 C++ 中连接位

ios - Swift - 即使我插入了不同的数字,文本字段也会返回 0

c++ - 隔离容易崩溃的 (SEGV) 但将关键的遗留代码加速到单独的二进制文件中

c++ - 使用 boost 在文件中查找正则表达式