C 数组未按应有方式随机化,值为负值

C 数组未按应有方式随机化,值为负值,c,arrays,random,time,C,Arrays,Random,Time,我尝试使用srand函数存储随机数,并使用循环将值存储在二维数组中。当我打印出数组时,它每次都有相同的值,而且数字经常是负值,这很奇怪,而且即使有srand函数,它们也保持不变 #include <stdio.h> #include <math.h> #include <time.h> #define NROW 13 #define NCOL 11 int main() { void disp_array(int a[NROW][NCOL]);

我尝试使用
srand
函数存储随机数,并使用循环将值存储在二维数组中。当我打印出数组时,它每次都有相同的值,而且数字经常是负值,这很奇怪,而且即使有
srand
函数,它们也保持不变

#include <stdio.h>
#include <math.h>
#include <time.h>

#define NROW 13
#define NCOL 11

int main()
{
    void disp_array(int a[NROW][NCOL]);

    int ar[NROW][NCOL];
    int i, j;

    for (i = 0; i < NROW; i++) {
        for (j = 0; j < NCOL; j++) {
            ar[NROW][NCOL] = (rand() % 101);
        }
    }
    disp_array(ar);

    return 0;
}

void disp_array(int a[NROW][NCOL])
{
    int i;
    int j;

    for (i = 0; i < 7; i++) {
        for (j = 0; j < 5; j++) {
            printf("Value at row %d column %d is %d \n", i, j, a[i][j]);
        }
    }
}
#包括
#包括
#包括
#定义第13行
#定义NCOL 11
int main()
{
void disp_数组(int a[NROW][NCOL]);
国际会计准则[NROW][NCOL];
int i,j;
对于(i=0;i
首先,语句
ar[NROW][NCOL]=(rand()%101)不正确,因为每次将数据分配到相同的
ar[NROW][NCOL]
中时,
NROW
&
NCOL
都没有变化

因此,将其替换为
ar[i][j]=(rand()%101)

其次,要打印数组元素,请按如下方式打印

for (i=0;i<NROW;i++){  /* don't use < 5 or < 7 if you have NROW & NCOL*/
        for(j=0;j<NCOL;j++){
               ar[i][j]= (rand()%101);
        }
} 

看到这一点,看看
ar[NROW][NCOL]=(rand()%101)再次。这是真的吗?你分配给
ar
中的哪个元素?另外,别忘了分配给prng。我解决了,我真是个白痴。你说的给prng播种是什么意思?
ar[NROW][NCOL]=(rand()%101)-->as
ar[i][j]=(rand()%101)
srand(getpid());/*getpid() returns process id and 
              every time process manager generates different process id*/