回 帖 发 新 帖 刷新版面

主题:fortran中有关contains语句,external语句,递归函数的一些问题?

各位大侠,小弟初学fortan有一些问题请教。
contains语句定义某些函数只能在某些特定的函数中调用。那么
contains 
  recursive integer function fact(n)result(ans)
函数fact只能在主程序中调用吗?他能自己递归吗?
external语句用来声明自定义函数,为什么下面的程序中写了integer,external::fact不能通过编译?
externa在遇到contains语句时不用写吗?

elemental函数的参数不能是数组?
比如:
real::a(10)=(/i,i=1,10/)
a=func(a)

elemental real function func(num)
  implicit none
  real,intent(in)::num
  func=sin(num)+cons(num)
return
end function

这个中func(a)这中用法不就是将一个数组作为参数吗?他的意思是不是num=a(1)?或者说不能将数组作为参数只是针对下面的子程序区域。那么我是不是可以写成a=func(a(3:5))从a(3)开始呢?


各位不吝赐教!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

program pp1
implicit none
integer ::n
integer,external::fact
write(*,*)'N,'
read(*,*)n
write(*,"(I2,'!=',I8)")n,fact(n)
pause

contains
recursive integer function fact(n)result(ans)
implicit none
integer,intent(in)::n
integer,save::count=1
integer::localcount,temp
localcount=count
count=count+1
write(6,"(I2,'th enter,n=',I2)")localcount,n
if(n<0)then
  ans=-1
  write(6,"(I2,'th exit,n=',I2,' ans=',I8)")localcount,n,ans
  return
else if(n<=1)then
  ans=1
  write(6,"(I2,'th exit,n=',I2,' ans=',I8)")localcount,n,ans
  return
end if
temp=n-1
ans=n*fact(temp)
  write(6,"(I2,'th exit,n=',I2,' ans=',I8)")localcount,n,ans
  return
end function fact

end program pp1

回复列表 (共3个回复)

沙发

elemental代表的是你可以传数组给这个函数,而这个函数会一个一个地处理这个数组的,并且是相互独立的(可并行)
external代表这后面声名的子程序是在别处定义的,不属于当前子程序的内部子程序:)
contains代表下面的子程序和函数包含在当前的“物件”里,属于当前“物件”的内部子程序或函数:)而这个“物件”可以是子程序、函数或者是模块等等:)

板凳

[quote]elemental代表的是你可以传数组给这个函数,而这个函数会一个一个地处理这个数组的,并且是相互独立的(可并行)
external代表这后面声名的子程序是在别处定义的,不属于当前子程序的内部子程序:)
contains代表下面的子程序和函数包含在当前的“物件”里,属于当前“物件”的内部子程序或函数:)而这个“物件”可以是子程序、函数或者是模块等等:)[/quote]
多谢啊,昨天看了会书,自己也明白了,感觉你比书里说的清晰一些

3 楼

书里不能像俺这样说啊,他要说的详细些才行的:)

我来回复

您尚未登录,请登录后再回复。点此登录或注册