2017-07-29 90 views
2

這是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?爲什麼當明確的所有款項相等時,控制權轉移到其他部分?

+1

['一個== b == ==ç...'不會做你所期望的(https://stackoverflow.com/q/8889522/995714) –

+0

在另一個註釋中,將變量和數組的元素'c [5],r [5],d1,d2'初始化爲0是很好的。雖然你的問題的實際錯誤在'if'語句中。 – MKR

+1

您的代碼在其中一個對角線上出現錯誤,請參閱我的更新答案。 –

回答

1

你不能像這樣鏈接相等運算符。表達

c[0] == c[1] 

計算結果爲01,所以表達式

c[0] == c[1] == c[2] 

  • c[0]c[1]相等只有真實的,c[2]是1,或
  • c[0]c[1]不相等,且c[2]是0

可以使用&&運算符(邏輯與)寫if聲明這樣

if (c[0] == c[1] && c[0] == c[2] && ... 
+1

您可以像這樣鏈接相等運算符,因爲該程序完成了它。但是,當你像這樣鏈接相等運算符時,它很少做你想要的。 –

+0

@JonathanLeffler LOL – user3386109

1

這並不因爲第一的結果工作==會是真或假,它不會等於第二個整數。您需要

If(c[1] == c[2] && c[2] == c[3] && c[3] == c[4] etc 

此外,您的第二個對角線計算的邏輯是不正確的。作爲x == y,ms [x] [y]與ms [y] [x]相同。你正在練習d1兩次!相反,你需要:

d2 += ms[4-x][y]; 
+0

其實它應該是'd2 + = ms [4-x] [y];' –

+0

是真的。更新它。 –

相關問題