如何在fortran 90中打印real和real8变量的所有小数?

时间:2016-09-02 16:33:15

标签: fortran fortran90

program hello
   real(kind=8) :: x
   x=1.000001234567890
   Write(*,'(F10.11)') X
end program Hello

写声明究竟是如何工作的?我尝试了几种组合,但无法弄明白。如果我不知道变量有多少小数,该怎么办?如何将所有数字打印到最后一个小数点?

2 个答案:

答案 0 :(得分:2)

以下程序会将浮点数打印到标准输出而不会丢失任何精度。

program main

  use ISO_Fortran_env, only: &
       stdout => OUTPUT_UNIT, &
       compiler_version, &
       compiler_options

    ! Explicit typing only
    implicit none

    ! Variable declarations
    integer, parameter :: SP = selected_real_kind(p=6, r=37)
    integer, parameter :: DP = selected_real_kind(p=15, r=307) 
    real (SP)          :: single
    real (DP)          :: double

    single = 1.000001234567890_SP
    double = 1.000001234567890_DP

    write( stdout, '(e13.6e2)') single
    write( stdout, '(e23.15e3)') double

    write( stdout, '(/4a/)') &
    ' This file was compiled using ', compiler_version(), &
    ' using the options ', compiler_options()

end program main

注意如何使用类型参数SPDP以便携方式控制精度。该计划产生:

0.100000E+01
0.100000123456789E+001

This file was compiled using GCC version 6.1.1 20160802 using the options -mtune=generic -march=x86-64 -std=f2008ts

答案 1 :(得分:1)

你的主要问题是' X.Y' X是总长度,Y是小数点右边的长度。所以X> Y,在你的情况下由2 ......应该是" 13.11"。

PROGRAM Hello
IMPLICIT NONE
REAL(kind=8) :: x  !Some suggest DOUBLE
x=1.000001234567890
WRITE(*,5) x
5 FORMAT('x=',F14.11)
WRITE(*,6) x             !This make be better for you...
6 FORMAT('x=',0PE22.11)  !This make be better for you...
END PROGRAM Hello