[Fortran] 纯文本查看 复制代码
program main
use library
implicit none
real::a,b!要声明subroutine
real::T(69,2)
character*30::ans
real,allocatable::y_nihe(:)
integer::i,error
n=69.0
!读SST文件
open(unit=10,file="Global_SST.txt")
do i=1,n
read(10,*) T(i,1:2)
x(i)=T(i,1)
y(i)=T(i,2)
print*,'x=',x(i),'y=',y(i)
end do
close(10)
call nihe(x,y,n,a,b,ans,y_nihe)!不能忘记
!建拟合后数值文件
open(unit=11,file="Global_SST_nihe.txt")
do i=1,n
write(11,*) x(i),y(i),y_nihe
end do
close(11)
end
module library
!real,allocatable,save::x(:),y(:)
real*8,allocatable,save::y(:)
integer,allocatable,save::x(:)
real,save::n!数据数
contains
!计算测试数据x(i)的平均值
real function average_x(x,n)
implicit none
real::sum1!输入参数
integer,allocatable::x(:)!要加(:)否则sub里调用会报错6637
integer::i
real::n
sum1=0.0
do i=1,n
sum1=sum1+x(i)
end do
average_x=sum1/n
return
end
!计算测试数据y(i)的平均值
real function average_y(y,n)
implicit none
real::sum2!输入参数
real*8,allocatable::y(:)!要加(:)否则sub里调用会报错6637
integer::i
real::n
sum2=0.0
do i=1,n
sum2=sum2+y(i)
end do
average_y=sum2/n
return
end
subroutine nihe(x,y,n,a,b,ans,y_nihe)
implicit none
real::a,b,ave_x,ave_y,suma,sumb,sumc,sumd,sume
real*8,allocatable,intent(in)::y(:)
integer,allocatable,intent(in)::x(:)
real,allocatable::y_nihe(:)
character*30,optional::ans
character*10::ac,bc
integer::i
real::n
ave_x=average_x(x,n)!测试数据平均值
ave_y=average_y(y,n)
!求b的公式计算
suma=0.0
do i=1,n
suma=suma+x(i)*y(i)
end do
sumb=0.0
do i=1,n
sumb=sumb+y(i)
end do
sumc=0.0
do i=1,n
sumc=sumc+x(i)
end do
sumd=0.0
do i=1,n
sumd=sumd+x(i)**2
end do
sume=sumc**2
!b的公式计算
b=(n*suma-sumb*sumc)/(n*sumd-sume)
!求a的公式计算
a=ave_y-b*ave_x
!曲线公式输出
write(ac,'(f5.3)')a!数字转字符串
write(bc,'(f5.3)')b
ans="y="//trim(ac)//"+"//trim(bc)//"*x"!要去空格,不然看不到ac后面的
!拟合y的计算
do i=1,n
y_nihe(i)=a+b*x(i)
end do
return
end subroutine
end module library
[Fortran] 纯文本查看 复制代码
do i=1,n
read(10,*) T(i,1:2)
x(i)=T(i,1)
y(i)=T(i,2)
print*,'x=',x(i),'y=',y(i)
end do