c++ 获得一个1-1000的随机数代码
时间: 2023-12-24 17:23:12 浏览: 71
可以使用C++的标准库中的随机数生成器和分布函数来生成1-1000的随机数。以下是一个示例代码:
```c++
#include <iostream>
#include <random> // 包含随机数生成器和分布函数的头文件
int main() {
// 创建一个随机数生成器
std::random_device rd;
std::mt19937 gen(rd());
// 创建一个分布函数,范围是1-1000
std::uniform_int_distribution<> dis(1, 1000);
// 生成随机数并输出
int random_num = dis(gen);
std::cout << "随机数为:" << random_num << std::endl;
return 0;
}
```
每次运行该程序,都会生成一个不同的1-1000之间的随机数。
相关问题
C++生成一个1-8的随机数然后用cout输出
好的,这是一个简单的代码段,它可以生成一个1-8的随机数并输出:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0));
int num = rand() % 8 + 1;
std::cout << "随机数为:" << num << std::endl;
return 0;
}
```
注意,我们使用了 `srand` 函数来设置种子,这样可以保证每次运行程序时都会得到一个不同的随机数。我们还使用了 `rand` 函数来生成随机数,并且通过 `%` 和 `+` 运算符将其缩放到1-8的范围内。最后,我们使用 `cout` 输出随机数。
用C++代码写1-10的随机数
可以使用rand()函数来生成1-10范围内的随机数,示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i;
/* 随机数种子初始化 */
srand((unsigned) time(NULL));
for(i = 0; i < 10; i++) {
int rand_num = rand() % 10 + 1; // 生成1-10范围内的随机数
printf("%d ", rand_num);
}
return 0;
}
```
该代码使用srand()函数初始化随机数种子,然后使用rand()函数生成0-9范围内的随机数,加1即可得到1-10范围内的随机数。循环10次,输出生成的随机数即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)