【发布时间】:2021-06-20 19:53:00
【问题描述】:
我正在编写代码,用 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;
}
}
【问题讨论】:
标签: c++ arrays loops for-loop integer