นี่คือโปรแกรม C++ สำหรับค้นหาฐานและมิติของเมทริกซ์ โปรแกรมนี้ใช้การคำนวณ determinant (ค่าเดทออร์มิแนนต์) เพื่อตรวจสอบว่าเวกเตอร์ต่างๆ สร้างฐานของปริภูมิเวกเตอร์ได้หรือไม่
อัลกอริทึม
Begin
Function determinant():
คำนวณ determinant ของเมทริกซ์
Arguments:
n = จำนวนองค์ประกอบ
matrix[10][10] = เมทริกซ์นำเข้า
declare submatrix[10][10]
// ส่วนเนื้อหาของฟังก์ชัน:
if (n == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]))
else
วนลูป for c = 0 ถึง n-1
ประกาศและเริ่มต้น submati = 0, submatj
วนลูป for i = 1 ถึง n-1
เริ่มต้น subj = 0
วนลูป for j = 0 ถึง n-1
if (j == c) continue
submatrix[submati][submatj] = matrix[i][j]
เพิ่ม subj
เพิ่ม submati
คำนวณ d = d + (pow(-1, c) * matrix[0][c] * determinant(n-1, submatrix))
End
ตัวอย่างโค้ด
#include <iostream>
#include <math.h>
using namespace std;
double d = 0;
double determinant(int n, double matrix[10][10]) {
double submatrix[10][10];
if (n == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
else {
for (int c = 0; c < n; c++) {
int submati = 0, submatj;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == c) continue;
submatrix[submati][submatj] = matrix[i][j];
subj++;
}
submati++;
}
d = d + (pow(-1, c) * matrix[0][c] * determinant(n - 1, submatrix));
}
}
return d;
}
int main(int argc, char **argv) {
cout << "Enter the number of elements:\n";
int n;
cin >> n;
double matrix[10][10];
cout << "Enter elements one by one:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[j][i];
}
}
d = determinant(n, matrix); // เรียกใช้ฟังก์ชัน
if (d != 0)
cout << "The elements form the basis of R" << n << " as the determinant is non-zero";
else
cout << "The elements don't form the basis of R" << n << " as the determinant is zero";
}
ผลลัพธ์ที่ 1
Enter the number of elements: 3 Enter elements one by one: 7 6 1 2 3 4 5 8 9 The elements form the basis of R3 as the determinant is non-zero
ผลลัพธ์ที่ 2
Enter the number of elements: 4 Enter the elements one by one: 7 6 1 4 2 3 5 4 9 8 2 3 2 1 3 0 The elements don't form the basis of R4 as the determinant is zero