用C++帮我写一个自定义函数,要求这个自定义函数里面实现一个真随机数,并返回一个int类型的真随机数。
时间: 2023-03-16 19:44:24 浏览: 53
#include <stdio.h>
#include <stdlib.h>
#include <time.h>int getRandomInt()
{
srand((unsigned)time(NULL));
return rand();
}int main()
{
printf("%d\n", getRandomInt());
return 0;
}
相关问题
用c++帮我写一个生成随机数的代码
以下是一个生成随机数的 C++ 程序示例:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand((unsigned)time(NULL)); // 初始化随机数种子
int num = rand() % 100 + 1; // 生成 1~100 的随机整数
cout << "随机数为:" << num << endl;
return 0;
}
```
程序首先使用 `srand()` 函数初始化随机数种子,然后使用 `rand()` 函数生成随机整数。这里使用了 `%` 运算符来将生成的随机数限制在 1~100 的范围内,也可以根据需要修改范围。
运行程序后,屏幕上会输出一个随机数。
请帮我用C++写一个生成1-100随机数的代码并写入特定txt文件
好的,以下是用C++生成1-100随机数并写入特定txt文件的代码:
```c++
#include <iostream>
#include <fstream>
#include <cstdlib> // 包含随机数生成函数rand()和srand()
#include <ctime> // 包含时间函数time()
using namespace std;
int main()
{
// 设置随机数种子为当前时间
srand(time(0));
// 打开文件
ofstream outFile("random.txt");
// 生成10个1-100的随机数并写入文件
for (int i = 0; i < 10; i++) {
int randNum = rand() % 100 + 1; // 生成1-100的随机数
outFile << randNum << endl; // 写入文件
}
// 关闭文件
outFile.close();
return 0;
}
```
以上代码生成10个1-100的随机数并写入名为“random.txt”的文件中。你可以根据需要修改生成的随机数数量和文件名。