[Fortran] 纯文本查看 复制代码
! NOTE:P209
! A sample code that reveals the principle of recursive functions and the calculation process
program ProgramName
implicit none
integer ExitKey
integer(kind=4) :: n
integer(kind=4), external :: fact
write(unit=6, fmt="('N = ')")
read (unit=5, fmt=*) n
write(unit=6, fmt="(I3,'! = ', I8)") n, fact(n)
! Avoid having the command window exit before the results are output
write ( *, *) 'Press input any words to exit...'
read ( *, *) ExitKey
stop
end program ProgramName
recursive integer(kind=4) function fact(n) result(ans)
implicit none
integer(kind=4), intent(in) :: n
integer(kind=4), save :: count = 1
integer(kind=4) :: localcount, temp
localcount = count
count = count + 1
write(unit=6, fmt="(I2, 'th enter, n = ', I2)") localcount, n
! The IF-ELSE combination of multiple judgments only executes the first module that matches the condition
! and then jumps to END IF to leave the statement.
if ( n < 0 ) then
ans = -1
write(unit=6, fmt="(I2, 'th exit, n = ', I2, 'ans = ', I8)") localcount, n, ans
return
else if ( n <=1 ) then
ans = 1
write(unit=6, fmt="(I2, 'th exit, n = ', I2, 'ans = ', I8)") localcount, n, ans
return
end if
temp = n - 1
ans = n * fact(temp)
write(unit=6, fmt="(I2, 'th exit, n = ', I2, 'ans = ', I8)") localcount, n, ans
return
end function fact
[Fortran] 纯文本查看 复制代码
integer(kind=4) :: n
integer(kind=4), external :: fact
integer::f
write(unit=6, fmt="('N = ')")
read (unit=5, fmt=*) n
f=fact(n)
write(unit=6, fmt="(I3,'! = ', I8)") n, f