为什么我得到的值超出了我的 rand 函数参数?

Why am I getting values that are outside of my rand function parameters?

我正在尝试使用函数输出 3 到 7 之间的 25 个随机值。每次我 运行 我的程序,我都会收到两个在这些参数范围内的值,但其余的值超出范围。

#include <iostream>
#include <iomanip>
using namespace std;

void showArray(int a[], int size);

void showArray(int a[], const int size)
{ 
    int i;
    
    for (i = 0; i < size; i++)
    {
        cout << a[i] << ", ";
    }
}
 

int main()
{
    //int iseed = time(NULL);
    //srand(iseed);

    srand(time(NULL));
    int randomNumb = rand() % 3 + 4;
    int array[]  = {randomNumb};

    showArray(array, 25);
}

这是我的输出:

4, 4, -300313232, 32766, 540229437, 32767, 0, 0, 1, 0, -300312808, 32766, 0, 0, -300312761, 32766, -300312743, 32766, -300312701, 32766, -300312679, 32766, -300312658, 32766, -300312287,

您只调用了 1 次 rand(),并将结果存储在 randomNumb 中,这是一个整数。

正在创建您的数组,其中只有 1 个元素 - randomNumb 的值。但是,您告诉 showArray() 该数组有 25 个元素,但事实并非如此。因此,showArray() 超出数组范围并显示周围内存中的随机垃圾。这是未定义的行为

如果你想要25个随机数,那么你需要分配一个可以容纳25个数字的数组,然后调用rand()25次来填充那个数组,例如:

#include <iostream>
using namespace std;

void showArray(int a[], const int size)
{ 
    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << ", ";
    }
}
 
int main()
{
    srand(time(NULL));

    int array[25];
    for(int i = 0; i < 25; ++i)
        array[i] = rand() % 3 + 4;

    showArray(array, 25);
}