[Fortran] 纯文本查看 复制代码
program S_equation
implicit none
integer::i,j,k,imax,t
real::max,n
!用矩阵(实型动态数组)将线性方程组表示出来!
real,dimension(:,:),allocatable::a,m
real,dimension(:),allocatable::x
write(*,*)'请输入线性方程组的元数n:'
read(*,*)t
!给动态数组分配内存!
allocate(a(t,t+1),m(t,t+1),x(t))
write(*,*)'请依次按行输入线性方程组的增广矩阵a:'
read(*,*)((a(i,j),j=1,t+1),i=1,t)
do k=1,t-1
!选取每列的最大列元素!
max=abs(a(k,k))
imax=k
do i=k+1,t
if(abs(a(i,k)).gt.max)then
max=abs(a(i,k))
imax=i
end if
end do
!将最大列元素所在的行与第K行进行交换!
do j=k,t+1
m(k,j)=a(k,j)
a(k,j)=a(imax,j)
a(imax,j)=m(k,i)
end do
!对方程组按X1,X2,...,Xt的顺序进行依次消元,将增广矩阵化为上三角矩阵!
do i=k+1,t
m(i,k)=a(i,k)/a(k,k)
do j=k+1,t+1
a(i,j)=a(i,j)-m(i,k)*a(k,j)
end do
end do
end do
!先算出Xt!
x(t)=a(t,t+1)/a(t,t)
!回带!
do k=t-1,1,-1
n=0
do j=t,k+1,-1
n=n+a(k,j)*x(j)
end do
x(k)=(a(k,t+1)-n)/a(k,k)
end do
write(*,*)'线性方程组的解为:'
do i=1,t
write(*,*)x(i)
end do
read(*,*)
end program S_equation