使用 rand() 的多维数组
我想创建一个只有两个值的多维数组:0 或 1。
我使用 srand/rand 函数,但数组仅包含 0。 这是代码:
#define NB_LINE 4
#define NB_COLUMN 11
int tab[NB_LINE][NB_COLUMN] ; // global variable
void generate() {
srand((unsigned int)time(NULL));
int n, i, j;
for(n = 0; n < NB_LINE*NB_COLUMN; ++n){
do
{
i = rand() % NB_LINE;
j = rand() % NB_COLUMN;
}
while (tab[i][j] != 0);
tab[i][j] = 1 ;
}
}
我不知道如何解决这个问题?
谢谢 !
编辑:谢谢您的回答。您认为 rand() 是否可能每列只有一个“1”而其他点仅包含 0 ?
I want to create a multidimensional array with just two values : 0 or 1.
I use the srand/rand functions but array contains only 0.
Here is the code :
#define NB_LINE 4
#define NB_COLUMN 11
int tab[NB_LINE][NB_COLUMN] ; // global variable
void generate() {
srand((unsigned int)time(NULL));
int n, i, j;
for(n = 0; n < NB_LINE*NB_COLUMN; ++n){
do
{
i = rand() % NB_LINE;
j = rand() % NB_COLUMN;
}
while (tab[i][j] != 0);
tab[i][j] = 1 ;
}
}
I don't know how to solve this problem ?
thanks !
Edit : Thanks for your answers. Do you think it's possible with rand() to have juste one "1" per column and others spots contain only 0 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的循环并没有按照你的想法去做。试试这个:
最后,你将得到一个数组,其中每个点随机有一个 1 或 0。
Your loop doesn't do what you think it does. Try this:
At the end of that, you will have an array where each spot randomly has a 1 or a 0.
您应该在生成的随机数上采用
%
和 2 。给出该提示后,尝试使程序更加简单且易于理解。为什么不按顺序填充数组的每个元素?You should take the
%
with 2 on a random number generated. With that hint given, try to make the program more simpler and easy to understand. Why don't you just fill each element of the array sequentially ?编辑的问题
是的当然。
不要循环遍历所有行和所有列,将每个单独的数组元素设置为
0
或1
的随机值,将所有数组元素初始化为 0(如果它们不是)还没有);循环遍历所有列并选择 1 个随机行并将相应的数组元素设置为1
。请注意,我已从
中删除了
srand()
生成()函数。每次程序调用时srand()
的调用次数不得超过一次(以保证最大的随机性)。实现此目的的最佳方法是从main()
调用srand
。另外,我将变量命名为
row
和col
,而不是i
和j
。而且,我将
tab
设为局部变量而不是全局变量。 尽可能避免全局变量:这是你帮自己的忙。如果没有全局变量,信息将通过参数传递给函数。Edited question
Yes, of course.
Instead of looping over all lines and all columns setting each individual array element to a random value of
0
or1
do initialize all array elements to 0 (if they aren't already); loop over all columns and choose 1 random line and set the corresponding array element to1
.Notice I've removed the
srand()
from thegenerate()
function.srand()
should be called no more than once per program invocation (to guarantee maximum randomness). The best way to accomplish that is to callsrand
frommain()
.Also, instead of
i
andj
, I named the variablesrow
andcol
.And, I've made
tab
a local variable rather than global. Avoid globals whenever possible: it's a favor you do yourself. With no globals the information is passed to the function through arguments.