[C++]N阶行列式计算

N阶行列式计算

#include 
using namespace std;
double matric[10][10] = {0};
// 注意这里的换值不是换指针!
void swaps(double* i, double* m) {
    double temp = *i;
    *i = *m;
    *m = temp;
}
int main() {
    int n;
    double answer = 1;
    cin >> n;
    for (int i = 0; i != n; i++) {
        for (int j = 0; j != n; j++) {
            cin >> matric[i][j];
        }
    }
    for (int i = 0; i != n; i++) {
        if (matric[i][i] == 0) {
            if (i == n - 1) {
                break;
            }
            for (int j = i + i; j != n; j++) {
                if (matric[j][i] != 0) {
                    for (int m = i; m != n; m++) {
                        swaps(&matric[i][m], &matric[j][m]);
                    }
                    answer *= (-1);
                    break;
                }
            }
        }
        for (int j = i + 1; j != n; j++) {
            if (matric[j][i] != 0) {
                double times = matric[j][i] / matric[i][i];
                for (int m = i; m != n; m++) {
                    matric[j][m] -= times * matric[i][m];
                }
            } else {
                continue;
            }
        }
    }
    for (int i = 0; i != n; i++) {
        answer *= matric[i][i];
    }
    if (answer - static_cast<int>(answer) >= 0.5) {
        answer++;
    } else if (answer - static_cast<int>(answer) <= -0.5) {
        answer--;
    }
    cout << static_cast<int>(answer) << endl;
    return 0;
}

此题最大的问题在于精度。使用double是最合适的。最精确。

答案:

#include 
using namespace std;

int n, **matrix;

int det(int **m, int size) {
    if (size == 2) return m[0][0]*m[1][1]-m[0][1]*m[1][0];
    int temp = 0;
    for (int i = 0; i < size; i++) {
        int **m0 = new int*[size-1];
        for (int v = 0; v < size-1; v++)
            m0[v] = new int[size-1];
        for (int p = 0; p < size-1; p++) {
            for (int q = 0; q < size-1; q++)
                if (q < i) m0[p][q] = m[p+1][q];
                else m0[p][q] = m[p+1][q+1];
        }
        // positive for even position and negative for odd position.
        if (i%2 == 0) temp += m[0][i]*det(m0, size-1);
        else if (i%2 == 1) temp -= m[0][i]*det(m0, size-1);
        // delete the int** we new before.
        for (int v = 0; v < size-1; v++) delete [] m0[v];
        delete [] m0;
    }
    return temp;
}

int main() {
    cin >> n;  // Matrix n * n ( n >= 2)
    matrix = new int*[n];
    for (int i = 0; i < n; i++) matrix[i] = new int[n];
    for (int i = 0; i < n*n; i++) cin >> matrix[i/n][i%n];
    cout << det(matrix, n) << endl;
    for (int i = 0; i < n; i++) delete [] matrix[i];
    delete [] matrix;
    return 0;
}

你可能感兴趣的:(C++编程)