【发布时间】:2016-01-10 06:18:02
【问题描述】:
我正在尝试创建一个 2D 数组 3x3 正方形。
计算和检查完成。 现在,我正在努力防止二维数组中出现重复数字。
我尝试使用 for 循环蛮力,但 cygwin 编译给我错误
下面是我的代码。 如何检查二维数组?
#include <stdio.h> /* printf */
/*Preprocessor*/
/*set N constant 3*/
#define N 3
typedef enum {false,true}
bool;
int main()
{
/*initialize size to 3*/
int size =3;
int sum, sum1, sum2,array[N][N];
int row, col = 0;
int i, j, duplicate =0;
/* variable to
indicate process reached*/
int checkf =0;
/*input into the array of an array*/
for(row =0; row <size; row++)
{
for(col =0; col < size; col++)
{
scanf("%d", &array[row][col]);
}
}
**/*check for repeated values*/
for(row =0; row<9; row++)
{
for(col=0; col <9; col++)
{
if(array==array[row][col])
}
}**
/*Diagonal*/
/*sum of diagonal from the left
equals to sum of diagonal
from the right */
/*initialize sum2 to 0*/
sum2 =0;
/*check if row less than 3*/
for(row=0; row< size; row++)
{
/*check if col less than 3*/
for(col=0;col<size; col++)
{
/*number of row
equals number of col*/
if(row == col)
{
/*addition*/
sum2 = sum2 + array[row][col];
}
}
}
/*row*/
/*check if row less than 3*/
for(row=0; row < size; row++)
{
/*initialize sum */
sum = 0;
/*check if col less than 3*/
for(col=0; col <size; col++)
{
/*addition of numbers*/
sum = sum + array[row][col];
}
/*check if all additions
adds up to same sum*/
if(sum2 == sum)
{
/*a flag or check to print*/
checkf =1;
}
else
{
/*a flag or check to print*/
checkf =0;
break;
}
}
/*Columns*/
/*check if row less than 3*/
for(row = 0; row < size; row++)
{
/*initialize sum */
sum1 =0;
/*check if col less than 3*/
for(col = 0; col < size; col++)
{
/*addition*/
sum1 = sum1 + array[col][row];
}
/*sum of diagonal equals
sum of columns*/
if(sum == sum1)
{
/*a flag or check to print*/
checkf =1;
}
else
{
/*a flag or check to print*/
checkf =0;
break;
}
}
/*if statement is true
prints and display*/
if(checkf ==1)
{
printf("This is a magic square.\n");
}
else
{
/*print and display*/
printf("This is not a magic square.\n");
}
return 0;
}
【问题讨论】:
-
"但是 cygwin 编译给我错误" -- 错误是什么?错误消息对我们非常有用。
-
if(array==array[row][col])看起来不对。您还需要两个循环来检查。见this answer -
嗨帅哥!我尝试应用之前的逻辑。我对 i 和 j 的工作原理感到困惑。