[英]Fixed size array not fixed
I'm using SRand/Rand to generate an array of random numbers. 我正在使用SRand / Rand生成随机数数组。 The array size depends on a number the user is prompted to put in. Basically, if the user puts in a size of 9, the array should be 9 numbers.
数组的大小取决于提示用户输入的数字。基本上,如果用户输入的大小为9,则数组应为9个数字。 This array should then be populated using rand() with a parameter to keep the array values less than 18. The problem is, a random size array is generated sometimes.
然后应使用rand()并使用参数填充该数组,以使该数组的值小于18。问题是,有时会生成一个随机大小的数组。 Maybe every 4th or 5th time I run the program the array might be 12-14 numbers.I can't see the problem with my code.
也许每第4或第5次运行该程序时,该数组就可能是12-14个数字。我看不到我的代码有问题。 I've included a snippet below.
我在下面包括了一个片段。 Anyone shed some light on it?
有人对它有所了解吗?
int main(void)
{
int N;
int i;
printf("Please enter a number\n");
scanf("%d", &N);
srand (time(NULL));
int numarray[N];
for(i=1; i<numarray[N]; i++)
{
numarray[i]=rand()%21;
printf("%d\n", numarray[i]);
}
return 0;
}
for(i=1; i<numarray[N]; i++)
You're looping over the wrong values. 您正在遍历错误的值。
numarray[N]
(which is just a value in the array, and is undefined in this case since it's one after the end of the array). numarray[N]
的值(这只是数组中的值,并且在这种情况下是未定义的,因为它在数组末尾为1)时,您将停止。 I suspect you want to do this: 我怀疑您想这样做:
for(i = 0; i < N; i++)
In this line of code: 在这行代码中:
for(i=1; i<numarray[N]; i++)
numarray[N]
is an uninitialized variable, so it has an unknown value. numarray[N]
是未初始化的变量,因此它具有未知值。 It could be zero, it could be 60,000. 它可以是零,也可以是60,000。
The result is that your loop runs for an unknown number of iterations. 结果是您的循环运行的迭代次数未知。
您实际上是要让for循环索引终止于numarray [N]而不是N吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.