如何在switch语句中使用随机生成的数字
How to use randomly generated number in switch statement?
我正在制作一个简单的程序,从我在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";
}
}
}
在括号中的switch语句中,您需要(rand() % 10) + 1
。在为随机数生成器设定种子后,rand()
函数将返回一个介于0和RAND_MAX
之间的数字。RAND_MAX
是一个很大的数字。
要得到一个范围内的随机数,一个标准的技巧是使用%
运算符。rand() % 10
返回一个介于0和9之间(包括0和9)的数字。加1可以得到1到10的范围。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 在C++中随机生成 20 个非重复数字
- 为什么我C++得到这个随机的奇怪数字
- C++:创建1000次唯一的随机分布,在任何分布中都没有重复的数字
- 如何编写一个递归函数,以随机的方式混淆从0到6的数字
- 奇怪的数字随机出现在输出中.(C++)
- 生成随机长度的数字字符串
- 随机生成的输出中有多少位数字 1、2、3
- 生成随机字符/数字
- 在随机生成的数组中查找重复的连续数字
- C++ 制作一个随机数字/字母生成器,代码中有问题
- 随机生成数字无法正常工作
- 随机数字双重类型
- 试图从文件中获取随机数字的总和
- 生成加起来为1的随机数字列表
- c++随机数字总是相同的,即使时间(0)作为种子
- C++随机数字游戏,rand正在选择一个不是来自该集的数字
- 生成部分有序的随机数字列表