2013-12-12 205 views
1

所以我將下面的代碼寫成程序來解決二維線性方程組。從2x3陣列矩陣計算行列式

#include <stdio.h> 

int main() 
{ 
    int eq[2][3]; 

    int D, Dx, Dy; 

    int sol[2]; 

    printf("Enter cofficients of first equation: "); 
    scanf("%d %d %d", &eq[0][0], &eq[0][1], &eq[0][2]); 

    printf("Enter cofficients of second equation: "); 
    scanf("%d %d %d", &eq[1][0], &eq[1][1], &eq[1][2]); 

    D = eq[0][0]*eq[1][1] - eq[1][0]*eq[0][1]; 
    Dx = eq[0][2]*eq[1][1] - eq[1][2]*eq[0][1]; 
    Dy = eq[0][0]*eq[1][2] - eq[1][0]*eq[0][2]; 

    if(D != 0){ 
    sol[0] = Dx/D; // x solution 
    sol[1] = Dy/D; // y solution 

    printf("x = %d, y = %d \n", sol[0], sol[1]); 
    } 
    else{ 
    printf("No unique solutions exist. \n"); 
    } 

    return 0; 
} 

我現在已經被委託使用原型轉換到這個函數:

bool determinantFunction(int e[][3], int s[]); 

我的問題是,我不知道從哪裏開始。我已經閱讀了儘可能多地在C中使用布爾值的方法,但我不明白如何或爲什麼要將它用於實現一個行列式函數。

+0

我相信我們將使用布爾返回值來確定解決方案是否實際計算。所以是的,它應該對非零行列式返回正確,對於零行列式應該返回錯誤。 – Ben

+0

「行列式」是從2×2(不是2×3)矩陣計算而來的。解決方案從2x3矩陣計算。 – chux

回答

0

這樣的功能可能有效的一種可能方式是,如果有獨特的解決方案,則返回true,否則返回false。如果解決方案確實找到了,它將被存儲在作爲第二個參數傳遞的數組中。

基本上,你只需將現有的代碼移入一個函數。您的sol數組將作爲第一個參數傳遞給您。

int main() 
{ 
    int eq[2][3]; 
    // ... 
    int sol[2]; 
    if (determinantFunction(eq, sol)) { 
     printf("%d %d\n", sol[0], sol[1]); 
    } else { 
     printf("No unique solutions exist.\n"); 
    } 
} 
+0

這也看起來像它的作品。非常感激! :) – Ben

1

所以,只是把現有的代碼在這樣的功能(我不是說你的代碼是正確的還是錯誤的),你喜歡的東西:

bool determinantFunction(int e[][3], int s[]) 
{ 
    int D, Dx, Dy; 

    // calculate determinant 
    D = e[0][0]*e[1][1] - e[1][0]*e[0][1]; 
    Dx = e[0][2]*e[1][1] - e[1][2]*e[0][1]; 
    Dy = e[0][0]*e[1][2] - e[1][0]*e[0][2]; 

    // if non-singular ... 
    if (D != 0) 
    { 
     // success 
     s[0] = Dx/D; // return x solution 
     s[1] = Dy/D; // return y solution 
     return true; 
    } 

    // no solution 
    return false; 
} 

那麼你main成爲東西這樣的(未測試):

int main() 
{ 
    int eq[2][3]; 
    int sol[2]; 

    printf("Enter cofficients of first equation: "); 
    scanf("%d %d %d", &eq[0][0], &eq[0][1], &eq[0][2]); 

    printf("Enter cofficients of second equation: "); 
    scanf("%d %d %d", &eq[1][0], &eq[1][1], &eq[1][2]); 

    if (determinantFunction(eq, sol)) 
    { 
     printf("x = %d, y = %d \n", sol[0], sol[1]); 
    } 
    else{ 
     printf("No unique solutions exist. \n"); 
    } 

    return 0; 
} 

對於示例:4X - 3Y = -14和3X - 5Y = -5,這是相同的:

4X - 3Y + 14 = 0
3倍 - 5Y + 5 = 0

你會得到:

result

好吧,最後更新 - 硬編碼係數:

int eq[2][3] = {{4, -3, 14}, {3, -5, 5}}; 
int sol[2]; 
if (determinantFunction(eq, sol)) 
{ 
    printf("x = %d, y = %d \n", sol[0], sol[1]); 
} 
else{ 
    printf("No unique solutions exist. \n"); 
} 
+0

舉個例子,我想解決這個方程組: (4x - 3y = -14) (3x - 5y = -5) 我該如何將它轉化爲函數調用? – Ben

+0

如果我想硬編碼這個方程組,我需要在main中做一個函數調用,對吧?我將如何去做呢? – Ben

+0

@Ben看到上面最後更新的答案....有幫助嗎? –