fortran - Fortran。使用检查素数的函数进行
问题描述
我最近在学习 Fortran,并试图制作一个程序来检查素数。该函数工作正常,没有任何循环。当给定数是素数时,它可以给出 1,否则为 0。但是,在 do while 循环中使用时不能正常工作。在 2 ~ 10 的范围内,它应该给出 1(对于 2)、1(对于 2)、0(对于 4)、1(对于 5)、0(对于 6)等。但是,它一直显示只有 0。我对编程很陌生,所以我不确定我错过了什么。我知道有很多与素数相关的答案,但我没有看到任何这样的问题。
**检查素数的功能**
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
** 结果 **
10 is prime number, so the return : 0
11 is prime number, so the return : 1
0
0
0
0
0
0
0
0
0
解决方案
对于 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
推荐阅读
- reactjs - 我的 git 在反应时没有被识别,我不知道为什么
- java - 如何在android中使用GraphView绘制实时数据
- loopbackjs - loopback4 通过命令行创建控制器而没有提示问题
- javascript - 地图标记未出现在网站上
- api - 在 Visual Studio 默认选项中添加 REST API 客户端
- unit-testing - 人们测试他们的 clojure.spec 规范是否常见?
- apparmor - 如何在不同命名空间的 ubuntu 20.04 下使用 snap?获得许可被拒绝错误
- windows - EnableDelayedExpansion、For 和带有特殊字符(如 ! % &
- python - 如何从“coinmarketcapapi.Response”类中提取“名称”?
- python - InvalidArgumentError:logits 和标签必须具有相同的第一维,得到 logits 形状 [80,16] 和标签形状 [1280]