用c++写一个随机点名程序
时间: 2023-10-20 22:08:56 浏览: 138
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
int main()
{
// 设置随机数种子
srand(time(0));
// 建立学生名单
vector<string> students = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"};
// 生成随机数,选出被点名的学生
int index = rand() % students.size();
string name = students[index];
// 输出被点名的学生
cout << "今天被点名的学生是:" << name << endl;
return 0;
}
相关问题
写一个关于随机点名的c++程序
好的,我可以回答这个问题。以下是一个简单的随机点名程序的 C 代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char *names[] = {"张三", "李四", "王五", "赵六", "钱七"};
int num_names = sizeof(names) / sizeof(names[]);
srand(time(NULL));
int random_index = rand() % num_names;
printf("随机点名结果是:%s\n", names[random_index]);
return ;
}
```
这个程序首先定义了一个字符串数组 `names`,里面存放了一些学生的名字。然后通过 `srand` 函数和 `time` 函数来初始化随机数生成器,确保每次运行程序时都会得到不同的随机结果。接着,程序使用 `rand` 函数生成一个随机数,再通过取模运算得到一个在 `names` 数组范围内的随机下标。最后,程序输出随机点名的结果。
希望这个程序能够帮到你!
用c++写一个随机生成整数
可以使用rand()函数来生成随机整数,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num;
srand(time(NULL)); // 初始化随机数种子
num = rand(); // 生成随机整数
printf("随机整数为:%d\n", num);
return 0;
}
```
这段代码会生成一个随机整数并输出。