c++ - 用指定范围内的随机数填充数组 (C++)

标签 c++ arrays loops for-loop integer

我正在编写代码,用 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/

相关文章:

c++ - 错误3错误LNK2019 : unresolved external symbol "public: void __thiscall

c++ - 使用邻接矩阵在 C++ 上的有向图中查找所有循环的算法

c# - 合并多个字节数组c#

php - 如何在mysql select查询中传递数组值

do-while 中的条件为 ||与&&

javascript - 如何重构这段代码?我有 3 个标签需要在列表中重新选择

c++ - VC编译C++模板代码时如何设置更严格的编译规则

c++ - 添加到我的程序的导入功能破坏了 OOP 封装。如何恢复封装?

JavaScript 杂货 list

php - 如何在循环遍历数组时将项目添加到数组?