Fortran浮点整数更改值

时间:2019-01-10 13:44:49

标签: fortran gfortran

我注意到我使用的代码中有一个错误,该错误由以下测试代码演示:

PROGRAM test

implicit none


integer(kind=8):: i

i=17159401
print*,i,float(i)


end program test

代码输出17159401 17159400.0,而它应该输出17159401 17159401.0

我正在使用gfortran:

Using built-in specs.
COLLECT_GCC=gfortran
COLLECT_LTO_WRAPPER=/apps/gcc/4.8.2/bin/../libexec/gcc/x86_64-unknown-linux-gnu/4.8.2/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: ../gcc-4.8.2/configure --prefix=/cm/shared/apps/gcc/4.8.2 --enable-languages=c,c++,fortran --with-gmp-include=/root/rpmbuild/BUILD/gcc-4.8.2-obj/../gcc-4.8.2/our-gmp --with-gmp-lib=/root/rpmbuild/BUILD/gcc-4.8.2-obj/../gcc-4.8.2/our-gmp --with-mpc-include=/root/rpmbuild/BUILD/gcc-4.8.2-obj/../gcc-4.8.2/our-mpc/src --with-mpc-lib=/root/rpmbuild/BUILD/gcc-4.8.2-obj/../gcc-4.8.2/our-mpc/src/.libs --with-mpfr-include=/root/rpmbuild/BUILD/gcc-4.8.2-obj/../gcc-4.8.2/our-mpfr/src --with-mpfr-lib=/root/rpmbuild/BUILD/gcc-4.8.2-obj/../gcc-4.8.2/our-mpfr/src/.libs
Thread model: posix
gcc version 4.8.2 (GCC) 

有任何想法为什么会这样?

1 个答案:

答案 0 :(得分:2)

默认实型在这里没有足够的准确性。

program test
  implicit none
  integer, parameter :: i10 = selected_int_kind(10)
  integer, parameter :: r15 = selected_real_kind(15)
  integer(kind=i10):: i
  real :: r
  real(kind=r15) :: s
  i=17159401
  r = i
  print *, 'default real kind: r', r, 'r+1', r+1, 'r-1', r-1
  s = i
  print *, 'r15 real kind: s', s, 's+1', s+1, 's-1', s-1
end program test

我收到的输出:

 default real kind: r   17159400.0     r+1   17159400.0     r-1   17159400.0    
 r15 real kind: s   17159401.000000000      s+1   17159402.000000000      s-1   17159400.000000000     

上面的结果意味着1低于默认类型的浮点变量的精度。在第二行中,我选择了一种更加准确的类型(此处为r15),足以满足您的需求。