Fortran:在函数中调用其他函数

eersoy93

我在Code :: Blocks:main.f95,example.f95的两个单独文件中编写了GNU Fortran代码。main.f95内容:

program testing

   use example

   implicit none
   integer :: a, b

   write(*,"(a)", advance="no") "Enter first number: "
   read(*,*) a

   write(*,"(a)", advance="no") "Enter second number: "
   read(*,*) b

   write(*,*) factorial(a)
   write(*,*) permutation(a, b)
   write(*,*) combination(a, b)

end program testing

example.f95内容:

module example


contains


  integer function factorial(x)

     implicit none
     integer, intent(in) :: x
     integer :: product_ = 1, i

     if (x < 1) then

        factorial = -1

     else if (x == 0 .or. x == 1) then

        factorial = 1

     else

        do i = 2, x
           product_ = product_ * i
        end do

        factorial = product_

     end if

  end function factorial


  real function permutation(x, y)

     implicit none
     integer, intent(in) :: x, y
     permutation = factorial(x) / factorial(x - y)

  end function permutation


  real function combination(x, y)

     implicit none
     integer, intent(in) :: x, y

     combination = permutation(x, y) / factorial(y)

  end function combination


end module example

当我运行此代码时,输​​出为:

Enter first number: 5
Enter second number: 3
     120
   0.00000000    
   0.00000000    

排列和组合功能无法正常工作。感谢您的回答。

高性能标志

我认为您已经犯下了Fortran著名的(对那些了解它的人)陷阱之一。但是在透露这一点之前,我必须问一下您做了多少测试?我运行了您的代码,得到了奇怪的结果,并想了一分钟...

然后我测试的factorial功能的几个小的值x,其产生

 factorial            1  =            1
 factorial            2  =            2
 factorial            3  =           12
 factorial            4  =          288
 factorial            5  =        34560
 factorial            6  =     24883200
 factorial            7  =    857276416
 factorial            8  =   -511705088
 factorial            9  =   1073741824
 factorial           10  =            0

这显然是错误的。因此,在寻求帮助之前,您似乎没有正确测试代码(如果有的话)。(我没有测试您的combinationpermutation功能。)

哦,时代,哦,道德

您已经product_在该行中初始化了变量

 integer :: product_ = 1, i

并且这自动意味着product_获取该属性,save以便将其值从调用到调用之间进行存储(gotcha!)。在每个调用的开始(第一个调用除外)product_,它具有上一个调用结束时的值。

解决方法很简单,不要初始化product_改变

 integer :: product_ = 1, i

 integer :: product_ , i
 ...
 product_ = 1

更简单的是不编写自己的阶乘函数,而是使用内在product函数,但这是另一回事了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章