【发布时间】:2022-01-12 01:41:18
【问题描述】:
我正在尝试使用函数输出 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, -370312701, -32766, -32701, , 32766, -300312658, 32766, -300312287,
【问题讨论】:
-
用
int array[] = {randomNumb};,数组中有多少个元素?阵列有多大?回答这些问题应该可以帮助您弄清楚为什么会有奇怪的数字 -
用你自己的话说,如果要输出25个随机值,需要选择多少次随机值?用您自己的话来说,您认为您当前的代码选择了多少次随机值?为什么?怎么样?
-
用你自己的话说,当你写
int array[] = {randomNumb};时,你期望array包含多少元素?为什么?你是如何指定元素的数量的?如果您尝试从该数组中输出 25 个值,您明白为什么会导致问题吗? -
请注意,尽管看起来很随机,但在对象边界之外读取并不是一个好的随机数生成器。
-
谢谢,现在一切都说得通了????