[Fortran] 纯文本查看 复制代码
program main
implicit none
real a
dimension a(3,4)
print*,"请输入增广矩阵:"
read(*,*) a
call gs(3,a)
pause
end
subroutine gs(n,m)
!n为线性方程组元数,m为初始增广矩阵.
implicit none
integer i,j,k,p,n
real max,m,t,x,s,l
dimension x(n),m(n,n+1),l(n,n+1)!m为初始增广矩阵,l 为化简消去过程中的增广矩阵
do k=1,n
!选主元
max=abs(m(k,k))
do i=k+1,n
if(abs(m(i,k))>=max)then
max=abs(m(i,k))
p=i
endif
enddo
if(p/=k)then
!交换增广矩阵的第k行和第p行
do j=k,n+1
t=m(k,j)
m(k,j)=m(p,j)
m(p,j)=t
enddo
endif
!矩阵化简
if(k<=n) then
do i=k+1,n
l(i,k)=m(i,k)/m(k,k)
do j=k,n+1
m(i,j)=m(i,j)-l(i,k)*m(k,j)
enddo
enddo
endif
enddo
continue
!回代
x(n)=m(n,n+1)/m(n,n)
do i=n-1,1,-1
s=m(i,n+1)
do j=i+1,n
s=s-x(j)*m(i,j)
enddo
x(i)=s/m(i,i)
end do
do i=1,n
write(*,10) x(i)
10 format(1x,f5.2)
enddo
return
end