⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pex3_16.cpp

📁 数据结构C++代码,经典代码,受益多多,希望大家多多支持
💻 CPP
字号:
#include <iostream.h>
#pragma hdrstop

#include "trimat.h"

// solve the triangular system A*X = C
void SolveEqn(const TriMat& A, double X[], double C[])
{		
	// matrix is numRows x numRows
	int i, j, numRows = A.GetDimension();
	double terms = 0;

	// if the determinate of the maxtix is 0, there is no unique solution
	if (A.DetMat() == 0.0)
	{
		cerr << "The system of equations does not have a unique solution!\n";
		return;
	}

	// find X[numRows-1], X[numRows-2], ..., X[0]
	for(i=numRows-1;i >= 0;i--)
	{
		terms = 0;
		// compute terms = A[i,i+1]*X[i+1] +...+A[i,numRows-1]*X[numRows-1]
		for (j = i + 1; j < numRows; j++)
			terms += A.GetElement(i,j) * X[j];
		// X[i] = (C[i]-terms)/A[i,i]
		X[i] = (C[i] - terms)/A.GetElement(i,i);
	}
}
	
void main(void)
{
	// declare a 3 x 3 triangular matrix
	TriMat A(3);
	// declare the right hand side and the unknowns
	double C[3], X[3];
  
	// fixed point output with exactly three decimal places
	cout.setf(ios::fixed);
	cout.precision(3);
	cout.setf(ios::showpoint);

	cout << "Enter a  3 by 3 triangular matrix\n";
	A.ReadMat();
	cout << endl;
  	
	cout << "Enter the right hand sides: ";
	for(int i=0;i < 3;i++)
		cin >> C[i];
	cout << endl;
	
	// solve the system A*X = C
	SolveEqn(A,X,C);
	
	cout << "X0 = " << X[0] << endl;
	cout << "X1 = " << X[1] << endl;
	cout << "X2 = " << X[2] << endl;
}

/*
<Run #1>

Enter a  3 by 3 triangular matrix
1 1 0
0 2 1
0 0 2

Enter the right hand sides: 4 1 6

X0 =   5.000
X1 =  -1.000
X2 =   3.000

<Run #2>

Enter a  3 by 3 triangular matrix
1  2  3
0 -7 -8
0  0 -4

Enter the right hand sides: 5 -14 0

X0 = 1.000
X1 = 2.000
X2 = 0.000
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -