我正在尝试使用 C 语言编写一个程序,使用嵌套 for 循环内的随机数生成器来生成给定街道上每个家庭的人数。
这应该非常简单,但是当我尝试将数据分配到数组中的位置时,For 循环不会停止。如果我把这部分拿出来,for循环就会正常完成。
这个可以工作,但不会分配任何数据(我正在使用指针测试和测试 2 来检查循环是否已停止。):
// populating the streets with kids
// Streets then houses, we are assuming that each street is uniform in number of houses
int KidsInStreet[9][24];
for(int o = 0; o <10; o++){
printf("Testing %d\n", o);
for(int j = 0; j < 25; j++){
// assign randnumber between 0 and 5 for no of kids
int r = rand() % 5;
// KidsInStreet[o][j] = r;
printf("Testing2 %d\n", j);
}
}
当我尝试分配数据时,循环不会停止:
// populating the streets with kids
// Streets then houses, we are assuming that each street is uniform in number of houses
int KidsInStreet[9][24];
for(int o = 0; o <10; o++){
printf("Testing %d\n", o);
for(int j = 0; j < 25; j++){
// assign randnumber between 0 and 5 for no of kids
int r = rand() % 5;
KidsInStreet[o][j] = r;
printf("Testing2 %d\n", j);
}
}
我不知道为什么会发生这种情况,因为它确实不应该成为问题。 非常感谢您的任何反馈:)
最佳答案
正如 @WeatherVane 在评论中指出的,在这一行 int KidsInStreet[9][24]
中,9
和 24
是元素的数量。
将该行更改为 int KidsInStreet[10][25];
可以解决问题:
#include "stdio.h"
int main(void) {
// Disable stdout buffering
setvbuf(stdout, NULL, _IONBF, 0);
printf("Hello World\n");
int KidsInStreet[10][25];
for(int o = 0; o <10; o++){
printf("Testing %d\n", o);
for(int j = 0; j < 25; j++){
// assign randnumber between 0 and 5 for no of kids
int r = rand() % 5;
KidsInStreet[o][j] = r;
printf("Testing2 o%d j%d\n",o, j);
}
}
return 0;
}
您可以在这里尝试代码:https://repl.it/EycD/1
关于c - 将随机数分配给二维数组时,嵌套 For 循环永远不会结束。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41401291/