簡體   English   中英

我正在嘗試從二維數組中找到對角線的總和。 但是獲取它的地址而不是它的價值。有人可以向我解釋一下嗎?

[英]I am trying to find sum of diagonal from 2d array. But getting its address instead of its value .Can anyone explain this to me?

我試圖對二維數組中的對角線值求和,但得到不同的 Output ( Total:4194438 )任何人都可以幫助我解決這個問題。

#include <stdio.h>
    
    int main(){
    int i,j,a,sum,total;
    
    int diagonal_arr[3][3];
    
     for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            scanf("%d",&a);
            diagonal_arr[i][j]=a;
    
        }
     }
    
     for(i=0;i<3;i++){
        for(j=0;j<3;j++){
    
            if(i==j){
               sum= printf("%d\n",diagonal_arr[i][j]);
                total+=sum;
            }
        }
        printf("\n");
     }
    printf("Total= %d ",total);
    
    }

輸出:

Total= 4194438

你要這個:

...
total = 0;    // initialize total to 0

for (i = 0; i < 3; i++){
    for (j = 0; j < 3; j++){    
        if (i == j){
           printf("%d\n", diagonal_arr[i][j]);   // you can remove this line
           total += diagonal_arr[i][j];         // add diagonal value
        }
    }
}
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM