Fortran 函数中单精度,双精度不匹配的错误

错误实例01:

program subroutine
      real*4  arr 
      arr=1.1

      call fun1(arr)

end



subroutine fun1(arr)

    real*8 arr 

    write(*,*)  arr 

end

情况下
主程序定义了一个 单精度的变量 arr ,赋值为1.1,
子函数的变量类型是双精度。
打印结果是
[root@localhost subroutine]# ./a.out
-1.39490411823145607E+195
[root@localhost subroutine]#

说明 尝试用 双精度的方式 去解释单精度时候, 会出现严重的错误。

经过测试 ,反过来, 用单精度的方式去解释 双精度时 ,也会发生这样的错误 。

结论。只有 两边的精度匹配时,才能得到预期的效果。
要么都是双精度。
要么都是单精度。

情况2
如果用 数字的情况下, 要用什么类型来 处理呢?
经测试, 如果是 1.1 这样的字面值, 就是单精度, 用 real*4 就可以。 real*8 就不行。
如果需要双精度 的字面值,要写成 1.1d0 ,这样用real*8 就可以。

参考http://www-classes.usc.edu/engr/ce/108/text/fbk01.htm

情况3
如果,就要需要一个单精度的数字,而输入偏偏是双精度 ,那怎么办呢?

program subroutine

      call fun1(1.1d0)

end



subroutine fun1(tmp)
    real*8 tmp 
    real*4 arr 
    write(*,*)  tmp 
    arr=tmp

    write(*,*)  arr 

end

应该像这个例子,先用相同的精度,把数字接过来, 再进行赋值。

例子3

program test
    real,external:: add  // 应该显示声明为 real*8
    real*8 arr 
    arr = add(1.1)

    write(*,*) arr 


end

real*8 function add(t)
    real t

    add=1.1

    return 
end

例子3 的输出也是错的。因为函数返回类型是 real*8,
但是在 主程序中, 声明的时候,是real, 并没有标明是real*8 ,在我的机器上,
real 和 real*4 的一个意思 ,所以也会出错。

你可能感兴趣的:(Fortran)