c语言中怎么定义m行n列的由0和1组成的随机二维数组??

rt 3q
m行n列其中的m和n需要自己输入的

m和n不确定,所以要在输入m和n后动态创建二维数组。举例代码如下:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void){
    int m,n,i,j;
    char **p;
    printf("Input m & n(>0 int)...\n");
    while(scanf("%d%d",&m,&n),m<=0 || n<=0)
        printf("Error, redo:\n");
    if((p=(char **)malloc(sizeof(char *)*m))==NULL){
        printf("Application memory failure...\n");
        exit(0);
    }
    for(i=0;i<m;i++)
        if((p[i]=(char *)malloc(sizeof(char)*n))==NULL){
            printf("Failed to create the array...\n");
            exit(0);
        }
    srand((unsigned)time(NULL));
    for(i=0;i<m;i++){//给二维数组赋随机01值并顺便打印出来
        for(j=0;j<n;printf("%2d",p[i][j++]=rand()%2));
        printf("\n");
    }
    for(i=0;i<m;free(p[i++]));
    free(p);
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-01-17
//m,n已知切为常数,int
a[m][n]
srand(time(NULL));
//初始化随机函数
for(int
i=0;i<m;i++)
{
for(int
j=0;j<n;j++)
{
int
temp=rand()%100+1;
if(temp>50)
a[i][j]=1;
else
a[i][j]=0;
}
}
//m,n不为常数
int
**a=new
int*[m]
for(int
i=0;i<m;i++)
*a=new
int[n];
srand(time(NULL));
//初始化随机函数
for(int
i=0;i<m;i++)
{
for(int
j=0;j<n;j++)
{
int
temp=rand()%100+1;
if(temp>50)
a[i][j]=1;
else
a[i][j]=0;
}
}
第2个回答  2019-04-13
#include<stdio.h>
#include<stdlib.h>
#define
M
5
#define
N
5
int
main()
{
int
i,j;
int
a[M][N];
srand(2);//修改srand种子就能产生不同的随机数
for(i=0;i<M;i++)
for(j=0;j<N;j++)
{
a[i][j]=rand()%2;
printf("%d
",a[i][j]);
}
return
0;
}
第3个回答  2010-01-15
#include<stdio.h>
#include<stdlib.h>
#define M 5
#define N 5

int main()
{
int i,j;
int a[M][N];
srand(2);//修改srand种子就能产生不同的随机数
for(i=0;i<M;i++)
for(j=0;j<N;j++)
{
a[i][j]=rand()%2;
printf("%d ",a[i][j]);
}
return 0;
}本回答被提问者采纳
第4个回答  2010-01-15
//m,n已知切为常数,int a[m][n]
srand(time(NULL)); //初始化随机函数
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
int temp=rand()%100+1;
if(temp>50)
a[i][j]=1;
else
a[i][j]=0;
}
}
//m,n不为常数
int **a=new int*[m]
for(int i=0;i<m;i++)
*a=new int[n];
srand(time(NULL)); //初始化随机函数
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
int temp=rand()%100+1;
if(temp>50)
a[i][j]=1;
else
a[i][j]=0;
}
}
相似回答