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
1487658269(1).jpg (56.63 KB, 下载次数: 300)
program S_equation implicit none
integer::i,k,imax,t
real::max,n
!用矩阵(实型动态数组)将线性方程组表示出来!
real,dimension(:,:),allocatable::a,b
real,dimension(:),allocatable::x,m
write(*,*)'请输入线性方程组的元数n:'
read(*,*)t
!给动态数组分配内存!
allocate(a(t,t+1),m(t+1),x(t),b(t,t+1))
write(*,*)'请依次按行输入线性方程组的增广矩阵a:'
read(*,*)( b(i,:),i=1,t)
a=b
do k=1,t-1
!选取每列的最大列元素!
max=maxval(a(k:,k))!abs(a(k,k))
imax=maxloc(a(k:,k),1) + k - 1
!将最大列元素所在的行与第K行进行交换!
m(k:) = a(k,k:)
a(k,k:) = a(imax,k:)
a(imax,k:) = m(k:)
!对方程组按X1,X2,...,Xt的顺序进行依次消元,将增广矩阵化为上三角矩阵!
do i=k+1,t
a(i,k+1:)=a(i,k+1:) - a(i,k)/a(k,k)*a(k,k+1:)
end do
end do
!先算出Xt!
x(t)=a(t,t+1)/a(t,t)
!回带!
do k=t-1,1,-1
n= sum( a(k,k+1:t)*x(k+1:) )
x(k)=(a(k,t+1)-n)/a(k,k)
end do
write(*,*)'线性方程组的解为:'
write(*,*) x
write(*,*) matmul( b(1:t,1:t) , reshape(x,[t,1]) )!//验证
read(*,*)
end program S_equation
fcode 发表于 2017-2-21 22:05
a(imax,j)=m(k,i)
改为
a(imax,j)=m(k,j)
欢迎光临 Fortran Coder (http://bbs.fcode.cn/) | Powered by Discuz! X3.2 |