Fortran。使用函数检查素数时执行此操作
我最近在学习Fortran,并试图制作一个程序来检查素数。该函数运行良好,没有任何循环。当给定的数字是素数时,它可以给出1,否则它可以给出0。但是,当它用于do while循环时,它不能正常工作。在2~10的范围内,它应该给出1(表示2)、1(表示2)、0(表示4)、1(表示5)、0(表示6)等等。但是,它一直只显示0。我对编程相当陌生,所以我不确定我错过了什么。我知道有很多关于素数的答案,但我看不出有这样的问题 **函数检查素数**Fortran。使用函数检查素数时执行此操作,fortran,Fortran,我最近在学习Fortran,并试图制作一个程序来检查素数。该函数运行良好,没有任何循环。当给定的数字是素数时,它可以给出1,否则它可以给出0。但是,当它用于do while循环时,它不能正常工作。在2~10的范围内,它应该给出1(表示2)、1(表示2)、0(表示4)、1(表示5)、0(表示6)等等。但是,它一直只显示0。我对编程相当陌生,所以我不确定我错过了什么。我知道有很多关于素数的答案,但我看不出有这样的问题 **函数检查素数** module prime_function contain
module prime_function
contains
integer function isPrime(inp_num)
implicit none
integer :: inp_num
integer :: i = 1
integer :: temp1 = 0
do while (i < inp_num)
i = i + 1
if(mod(inp_num, i) == 0) then
exit
end if
end do
if(inp_num == i) then
temp1 = 1
else
temp1 = 0
end if
isPrime = temp1
end function
end module
program fortran_q
use prime_function
implicit none
integer :: ii, a
a = isPrime(10)
print *, "10 is prime number, so the return : ", a
a = isPrime(11)
print *, "11 is prime number, so the return : ", a
ii = 1
do while (ii < 10)
ii = ii + 1
print *, isPrime(ii)
end do
end program
对于刚接触Fortran的人来说,您有一个经典问题。
i
和temp0
的初始化意味着SAVE
属性。第一次调用isPrime
时,值设置为1和0。在下一次调用中,i
和temp0
的值被设置为上次执行isPrime
时它们之前的值。程序修复了这个问题
module prime_function
implicit none
private
public isprime
contains
function isPrime(inp_num) result(res)
integer res
integer, intent(in) :: inp_num
integer i, temp1
i = 1
temp1 = 0
do while (i < inp_num)
i = i + 1
if (mod(inp_num, i) == 0) exit
end do
res = 0
if (inp_num == i) res = 1
end function
end module
program fortran_q
use prime_function
implicit none
integer :: ii, a
a = isPrime(10)
print *, "10 is prime number, so the return : ", a
a = isPrime(11)
print *, "11 is prime number, so the return : ", a
ii = 1
do while (ii < 10)
ii = ii + 1
print *, isPrime(ii)
end do
end program
模素数函数
隐式无
私有的
公害
包含
函数isPrime(inp_num)结果(res)
整数分辨率
整数,意图(in)::inp_num
整数i,temp1
i=1
temp1=0
执行时(i
感谢您给出了清晰的答案!
module prime_function
implicit none
private
public isprime
contains
function isPrime(inp_num) result(res)
integer res
integer, intent(in) :: inp_num
integer i, temp1
i = 1
temp1 = 0
do while (i < inp_num)
i = i + 1
if (mod(inp_num, i) == 0) exit
end do
res = 0
if (inp_num == i) res = 1
end function
end module
program fortran_q
use prime_function
implicit none
integer :: ii, a
a = isPrime(10)
print *, "10 is prime number, so the return : ", a
a = isPrime(11)
print *, "11 is prime number, so the return : ", a
ii = 1
do while (ii < 10)
ii = ii + 1
print *, isPrime(ii)
end do
end program