如果我只使用我的功能一次,它可以正常工作。如果我让它做一个像下面的循环,四行注释代码,我的代码出现故障。我无法弄清楚为什么它会在初始值之后为每个其他数字返回T或F.
Asterisks在WRITE和READ的括号中,但由于某种原因它不会出现在这里。
PROGRAM PRIME
INTEGER :: N = 0, i = 1,x = 0
LOGICAL :: IP
WRITE (*,*) "Enter a number:"
READ (*,*) N
!DO WHILE ( N < 1000)
IP = IsPrime(N)
WRITE (*,*) IP, N
!N = N + 1
!END DO
read(*,*) x
CONTAINS
FUNCTION IsPrime(N)
LOGICAL :: IsPrime
INTEGER, INTENT(IN) :: N
IsPrime = .TRUE.
IF (N == 2) THEN
WRITE (*,*) N
ELSE
DO WHILE (i <= (N/2))
i = i + 2
IF (mod(N,i) == 0) THEN
IsPrime = .FALSE.
END IF
END DO
END IF
RETURN
END FUNCTION IsPrime
END PROGRAM PRIME
答案 0 :(得分:1)
You're forgetting to reset i
to 1 during each call to IsPrime
.
The first time IsPrime
is called, i=1
from the top of program main
. However, i
is incremented during the first IsPrime
call to something other than 1
so the second call starts with i/=0
.
Note that because IsPrime
is contain
ed within program main
, IsPrime
inherits i
from program main
.
I'm also bound to remind you to use implicit none
everywhere to avoid other errors, although it's not a problem in this case.