這是C程序,用來檢查矩陣是否爲幻方。 所有行和列的總和以及兩個對角線的總和等於65.這在printf語句中顯示。然而,if-else返回0而不是1.爲什麼?爲什麼在我的Magic Square程序中不工作
#include<stdio.h>
int c[5], r[5];
int d1, d2;
int ms[5][5] = {
{25, 13, 1, 19, 7},
{16, 9, 22, 15, 3},
{12, 5, 18, 6, 24},
{8, 21, 14, 2, 20},
{4, 17, 10, 23, 11}};
//to calculate sums of every row, column and both diagonals
void sumUp() {
for (int x = 0; x < 5; x++)
for (int y = 0; y < 5; y++) {
r[x] += ms[x][y];
c[x] += ms[y][x];
if (x == y) {
d1 += ms[x][y];
d2 += ms[y][x];
}
}
}
//prints sums calculated
//returns 1 if all sums equal
int isMagic() {
printf("\n%d", r[0]);
printf("\n%d", r[1]);
printf("\n%d", r[2]);
printf("\n%d", r[3]);
printf("\n%d", r[4]);
printf("\n%d", c[0]);
printf("\n%d", c[1]);
printf("\n%d", c[2]);
printf("\n%d", c[3]);
printf("\n%d", c[4]);
printf("\n%d", d1);
printf("\n%d", d2);
//every sum prints equal to 65
if (c[0] == c[1] == c[2] == c[3] == c[4] == r[0] == r[1] == r[2] == r[3] == r[4] == d1 == d2) //yet this does not work
return 1;
else
return 0;
}
void show() {
if (isMagic())
printf("\nYes, Magic");
else
printf("\nNot Magic");
}
int main() {
sumUp();
show();
return 0;
}
確切地說,爲什麼if-else返回0?爲什麼當明確的所有款項相等時,控制權轉移到其他部分?
['一個== b == ==ç...'不會做你所期望的(https://stackoverflow.com/q/8889522/995714) –
在另一個註釋中,將變量和數組的元素'c [5],r [5],d1,d2'初始化爲0是很好的。雖然你的問題的實際錯誤在'if'語句中。 – MKR
您的代碼在其中一個對角線上出現錯誤,請參閱我的更新答案。 –