GNU FortranコードをCode :: Blocksのmain.f95、example.f95という2つの別々のファイルに書きました。 main.f95内容:Fortran:関数内の他の関数を呼び出す
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
順列と組み合わせの機能が動作しません。正しく。答えをありがとう。
これは、多くのC/C++プログラマーを驚かせるものです。 'integer :: i = 42'は' integer :: i;と等しくない。 i = 42'ではなく、 'save :: i = 42'の代わりに使用します。 'i'の値は呼び出し間で維持され、決して42にリセットされません。 – jlokimlin