Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ แทนสมการเชิงเส้นในรูปแบบเมทริกซ์

นี่คือโปรแกรม C++ สำหรับแทนสมการเชิงเส้นในรูปแบบเมทริกซ์ โปรแกรมรับจำนวนตัวแปรและสัมประสิทธิ์ แล้วแสดงในรูปแบบเมทริกซ์

อัลกอริทึม

Begin
  1) รับจำนวนตัวแปร n และสัมประสิทธิ์ของแต่ละตัวแปร
  2) ประกาศ matrix[n][n] และ constant[n][1]
  3) วนลูป for i = 0 ถึง n-1 และ j = 0 ถึง n-1
     เพื่อรับสัมประสิทธิ์เป็นองค์ประกอบของเมทริกซ์
  4) แสดงเมทริกซ์โดยใช้ nested for loops
End

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

int main(void) {
  char variable[] = { 'x', 'y', 'z', 'd' };
  cout << "Enter the number of variables in the equations: ";
  int n;
  cin >> n;
  cout << "\nEnter the coefficients of each variable for each equation, ax + by + cz + ... = d:";
  int matrix[n][n];
  int constant[n][1];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      cin >> matrix[i][j];
    }
    cin >> constant[i][0];
  }
  cout << "Matrix representation is: " << endl;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      cout << " " << matrix[i][j];
    }
    cout << " " << variable[i];
    cout << " = " << constant[i][0];
    cout << "\n";
  }
  return 0;
}

ผลลัพธ์

Enter the number of variables in the equations: 3
Enter the coefficients of each variable for each equation, ax + by + cz + ... = d:
1 2 3 4 5 6 7 9 8 5 2 1
Matrix representation is:
1 2 3 x = 4
5 6 7 y = 9
8 5 2 z = 1