c++中生成一个字符串数组取随机数的方法并在main函数中执行for调用。
下面是一个示例代码,可以生成一个长度为10的字符串数组,每个元素都是一个随机数:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
const int n = 10; // 字符串数组长度
string arr[n]; // 字符串数组
srand(time(NULL)); // 设置随机数种子
// 生成随机数并将其转换为字符串存入数组中
for (int i = 0; i < n; i++) {
int num = rand(); // 生成随机数
arr[i] = to_string(num); // 转换为字符串并存入数组
}
// 输出数组中的元素
for (int i = 0; i < n; i++) {
cout << arr[i] << endl;
}
return 0;
}
在这个示例代码中,我们使用了 srand(time(NULL)) 来设置随机数种子,这样可以保证每次运行程序时生成的随机数序列都不同。然后使用 rand() 生成随机数,并用 to_string() 将其转换为字符串,最后存入字符串数组中。最后再用 for 循环输出数组中的每个元素
原文地址: https://www.cveoy.top/t/topic/eCDv 著作权归作者所有。请勿转载和采集!