【发布时间】:2021-04-03 07:17:04
【问题描述】:
我的函数应该随机插入一个用户选择的数字 1 到我的矩阵中。困难在于如果一个单元格包含 1,则它周围的单元格必须设置为 0。为什么我的代码打印错误的数字 1?在下面的代码中,我曾想过首先将整个矩阵设置为 0,然后随机生成一个设置为 1 的单元格,在检查它包含 0 并且该单元格与其他包含 1 的单元格之间的距离 >= 1。所有这样做直到用户输入的数字 m 变为 0。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void initialize(int n, int a[n][n]);
void createMap(int n, int a[n][n], int m);
int check (int i, int j, int v, int w);
void print(int n, int a[n][n]);
int main(){
int n;
printf("Insert square matrix size: ");
scanf("%d", &n);
int m;
printf("Insert 1s number: ");
scanf("%d", &m);
int a[n][n];
initialize(n,a);
createMap(n,a,m);
}
//Filling the matrix with 0
void initialize(int n, int a[n][n]){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
a[i][j] = 0;
}
}
}
//Setting in random position 1 value
void createMap(int n, int a[n][n], int m){
int x1; int x2;
int b[0][0];
while (m > 0){
int i = rand() % n;
int j = rand() % n;
if (a[i][j] == 0 && (check(i,j,x1,x2) == 1)){
a[i][j] = 1;
m--;
//I have to fill b array with coordinates and then to pass
//b array to check function to do the check in the whole b array
}
}
print(n,a);
}
//checking if I can set the value to 1
int check (int x1, int y1, int x2, int y2){
if (sqrt(pow((x1-x2),2) + pow((y1-y2),2)) >= 1){
return 1;
} else {
return 0;
}
}
//Printing the matrix
void print(int n, int a[n][n]){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
printf("\t%d",a[i][j]);
}
puts("");
}
}
【问题讨论】:
标签: arrays c function matrix random