我正在编写代码,用 0 到 9 范围内的随机数填充一个大小为 10 个整数的数组。我的代码可以工作,但它用完全相同的随机整数填充所有 10 个槽,有没有办法随机化每个数组项的整数?
这是我的代码:
#include <iostream>
#include <ctime>
#include <time.h>
using namespace std;
void initialize(int arr[], int size);
int main(){
const int SIZE = 10;
int myList[SIZE];
initialize(myList, SIZE);
return 0;
}
void initialize(int arr[], int size){
srand(time(0));
int random = (rand() % 9);
for(int i = 0; i < size; i++){
arr[i] = random;
}
for(int j = 0; j < size; j++){
cout<<arr[j]<< endl;
}
}
最佳答案
您在每次初始化中使用完全相同的整数。 for循环应该是这样的
for(int i = 0; i < size; i++){
arr[i] = (rand() % 10);
}
关于c++ - 用指定范围内的随机数填充数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66775367/