我在兩個單獨的文件Code :: Blocks中編寫了GNU Fortran代碼:main.f95,example.f95。 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;我= 42',而是'integer,保存:: i = 42'。 「i」的值在呼叫之間保持不變,並且不會重置爲42。 – jlokimlin