如何让Fortran识别函数返回类型?阶乘函数编译报错如何解决
问题原因
你在主程序中开启了implicit none规则,编译器不会自动根据变量/函数名首字母推定类型,而你没有在主程序作用域内声明外部函数factorial的返回值类型,因此编译器无法识别该函数的返回类型,抛出对应的编译错误。
解决方法
不需要使用interface或者module,只需要在主程序的变量声明区,将factorial声明为返回值为整数的外部函数即可,只需新增一行声明integer, external :: factorial。
修改后的完整代码
program functions implicit none integer :: fact integer, external :: factorial ! 新增的外部函数声明行 fact = factorial(5) print *, fact end program functions recursive function factorial(n) result(factResult) implicit none integer :: n integer :: factResult if (n == 0 .or. n == 1) then factResult = 1 else factResult = n * factorial(n - 1) end if end function factorial
使用gfortran编译上述代码可以正常通过,运行后输出结果为120,符合5的阶乘的计算预期。
内容的提问来源于stack exchange,提问作者Axel Pantoja
相关产品推荐
相关产品推荐

