fortran用子例行程序的方法设计一个程序,求 50~100 内的所有素数及其 和,
时间: 2024-09-30 14:04:51 浏览: 34
Fortran是一种主要用于数值计算的编程语言,我们可以使用子例行程序(Subroutine)来编写这个程序。以下是简单的步骤:
首先,我们声明一个函数`is_prime`用于判断一个数是否为素数,然后在主程序`main_program`中循环遍历指定范围内的数字,并调用`is_prime`函数。
```fortran
! 定义一个布尔型子例行程序 is_prime, 检查一个数是否为素数
subroutine is_prime(n, result)
integer, intent(in) :: n
logical, intent(out) :: result
if (n <= 1) then
result = .false.
else if (n == 2) then
result = .true.
else if (mod(n, 2) == 0) then
result = .false.
else
integer :: i
result = .true.
do i = 3, int(sqrt(n)) + 1, 2
if (mod(n, i) == 0) then
result = .false.
exit
end if
end do
end if
end subroutine is_prime
! 主程序 main_program,求 50 到 100 的素数和
subroutine main_program()
integer :: n, sum_of_primes, i
sum_of_primes = 0
do i = 50, 100
call is_prime(i, prime)
if (prime) then
write(*,*) "Prime number:", i
sum_of_primes = sum_of_primes + i
end if
end do
write(*,*) "Sum of primes between 50 and 100:", sum_of_primes
end subroutine main_program
! 执行主程序
call main_program()
! 注意:上述代码只是一个简化的示例,实际运行时可能需要包含错误处理和更完善的输出格式。
```
阅读全文
相关推荐











