2017-05-28 100 views
2

我正在学习正确使用子程序,函数和模块,下面是一个简单的例子,编译时没有发生错误,执行后,结果是4.57187637E-41而不是pi,我查了几个引用,还没有发现错误。Fortran中包含子程序和函数的模块

module wz 
    implicit none 
    private 
    public :: print_out 
    real,parameter :: pi = 3.14159 
    contains 
     subroutine print_out 
     implicit none 
     real :: area 
     print *, area 
     end subroutine print_out 

     function f(x) result(area) 
     implicit none 

     real, intent(in):: x 
     real   :: area 

     area = pi * x ** 2 
     end function f 
end module wz 

program test_module 
use wz 
implicit none 
    real :: x 
    x = 1. 
    call print_out 
end program test_module 
+0

怎么啦?预期的结果是什么?请阅读[问]。 –

回答

2

您正在打印的值是area,只是在声明之后以及在做任何事情之前。你需要传递xf功能,你可以做到这一点通过print_out子程序:

module wz 
    implicit none 
    private 
    public :: print_out 
    real,parameter :: pi = 3.14159 
    contains 
     subroutine print_out(x) 
     implicit none 
     real, intent(in) :: x 
     real :: area 
     area = f(x) 
     print *, area 
     end subroutine print_out 

     function f(x) result(area) 
     implicit none 

     real, intent(in):: x 
     real   :: area 

     area = pi * x ** 2 
     end function f 
end module wz 

program test_module 
use wz 
implicit none 
    real :: x 
    x = 1. 
    call print_out(x) 
end program test_module 
+0

谢谢。有没有办法,就像我可以给变量添加一些属性,以避免这种错误,然后编译器会提示一个特定的错误。 – ComplicatedPhenomenon

+0

打印仅声明的变量的错误?我不这么认为。当声明一个变量时,会为该变量分配一些内存并分配一个“垃圾”值(通常非常接近0)。 –

+0

是的。有一个完整的开关 - 检查未初始化或类似的东西。一旦调试完成,我拥有所有make文件并且不使用检查和警告。 - 检查界限或 - 检查所有和-warn界面也很有用。 – Holmz