2010-09-12 30 views
1

所以我試圖乘以c中的矩陣。但是,當我嘗試乘以兩個數組中的數字,並將它們放入答案數組中時,它始終爲零。繼承人的方法的代碼,謝謝。使用c中的結構變量賦值的問題

我的矩陣結構:

typedef struct matrix { 
int r; 
int c; 
double **mat; 
} *matrix_t; 

我的矩陣相乘方法:

matrix_t mat_mult(matrix_t a, matrix_t b) 
{ 
int i, j, k; 
double x, temp1, temp2; 
double tempsol = 0.0; 
x = temp1 = temp2 = 0; 
matrix_t answer; 

if(a -> c == b -> r) 
{ 
    answer = mat_new(a -> r, b -> c); 

    for(i = 0; i < a -> r; i++) 
     for(j = 0; j < b -> c; j++) 
     { 

      for(k = 0; k < a -> c; k++) 
      { 
       tempsol += a->mat[i][k] * b->mat[k][j]; 
       answer-> mat[i][j] = tempsol; 
      } 

     } 

return answer; 
} 
else if(a -> r == b -> c) 
{ 
    answer = mat_new(a -> c, b -> r); 
    return answer; 
} 
else 
{ 
    printf("Matrices could not be multiplied"); 
    exit(1); 
    return; 
} 
} 

繼承人我mat_new代碼以及

matrix_t mat_new(int r,int c) 
{ 
int i = 0; 
double **a; 
matrix_t matrix_a; 

a = (double**)malloc(r *sizeof(double *)); 
for(i = 0; i < r; i++) 
{ 
    a[i] = (double*)malloc(c *sizeof(double)); 
} 
matrix_a = (matrix_t) malloc (sizeof(struct matrix)); 
matrix_a -> mat = a; 
matrix_a -> r = r; 
matrix_a -> c = c; 

return matrix_a; 
} 
+0

代碼在代碼塊中不正確。你應該編輯並更正那個。此外,只是好奇,你是否正確地爲雙**墊分配內存? – Goutham 2010-09-12 23:06:50

+0

是啊,我相信內存分配正確,它可以存儲值和打印它們,但由於某種原因,在這種方法中,它不會讓我從其他兩個矩陣乘以數字並將其放入「答案」矩陣。如果我添加它,它可以工作,但是乘法什麼也不做。 – jbernie2 2010-09-12 23:14:04

+0

我是這個網站的新手,你是什麼意思,它不正確的代碼塊。 – jbernie2 2010-09-12 23:15:12

回答

0

好像你所有的問題在矩陣值讀數爲整數,而不是雙打幹。如果將read_mat()中的temp更改爲int,則一切正常,然後在將其放入矩陣中時將其轉換爲double。

-1

您的代碼不包含任何明顯錯誤。也許問題在於你的mat_new()。您在矩陣結構中定義mat的方式爲double **mat;,我不建議這樣做,可能會導致一些問題。

要分配一個2x2矩陣墊,你需要做的:

mat = new (double*)[2]; 
mat[0] = new double[2]; 
mat[1] = new double[2]; 

或正由M矩陣:

mat = new (double*)[n]; 
for (int i=0;i<n;i++) { 
    mat[i] = new double[m]; 
} 

這是你在做什麼?

+0

這是我的mat_new方法,我不使用你使用的方法,但是如果你的方法更好,我顯然會,反正,繼承人mat_new – jbernie2 2010-09-12 23:23:51

+0

你怎麼輸入更多的代碼? – jbernie2 2010-09-12 23:24:10

+0

我在上面的代碼中包含了mat_new。 – jbernie2 2010-09-13 00:08:27

1

您需要free您的對象。您需要重置tempsol。但最重要的是,您需要查看您的mat_mult()

matrix_t mat_mult(matrix_t a, matrix_t b) 
{ 
/* ... */ 
if(a -> c == b -> r) 
{ 
    /* ... */ 
} 
else if(a -> r == b -> c) 
{ 
            /* BZZZZT!     */ 
    answer = mat_new(a -> c, b -> r); /* BZZZZT! mat_mult(b, a); */ 
            /* BZZZZT!     */ 
    return answer; 
} 
else 
{ 
    /* ... */ 
} 
} 
0

這應該爲你工作,例如:

matrix_t mat_new(int r,int c) 
{ 
    matrix_t new = malloc(sizeof*new); 
    new->r = r; 
    new->c = c; 
    new->mat = malloc(r*c*sizeof(double)); 
    return new; 
}