本文介绍了定义一个必须声明为常量但在循环中更改的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试函数 selected_real_kind 的值范围(仅用于踢球时为-1:34),以确定其返回的 kind 参数和实际值使用此种类定义的变量使用的精度位.不过,由于要转换变量 x u alpha的函数,我仍然在下面定义变量 RP (例如 real(x,RP)例如)要求 RP (种类类型)必须是常量.

I'm testing out ranges of values (-1:34 just for kicks) for the function selected_real_kind to determine the kind parameter it returns and the actual number of bits of precision used by a variable defined using this kind. I'm stuck with how to define variable RP below, though, since the function to convert the variables x, u and alpha (real(x,RP) e.g.) require that RP (the kind type) to be constant.

如果我将RP定义为参数,即在顶部写 integer,parameter :: RP ,则必须立即对其进行初始化,然后显然可以"不能更改它,因为它是一个 parameter ,所以这行不通.

If I define RP to be a parameter, i.e. at the top write integer, parameter :: RP I have to initialize it immediately, and then I obviously can't change it because, well, it's a parameter, so this won't work.

这就是我所拥有的:

program f1
  implicit none
  integer :: n,t  ! n used in selected_real_kind(n), t is precision (#bits)
  integer :: RP
  real :: x=1.5, u=1.0, alpha=1.0  ! will be reset using _RP below

  print '(A2,A4,A4)', "n", "RP", "t"  ! header for values

  do n=-1,34
     RP = selected_real_kind(n)

     ! convert x,u,alpha to type RP.  These functions throw the error!
     x = real(x,RP)
     u = real(u,RP)
     alpha = real(alpha,RP)

     ! init precision test variables
     x=1.5_RP
     u=1.0_RP
     alpha=1.0_RP

     ! reset precision value to zero before each test
     t = 0

     ! precision test
     do while(x>alpha)
        u = u/2.0_RP
        x = alpha+u
        t = t+1
     end do

     print '(I2 I4 I4)', n, RP, t
  end do

end program f1

推荐答案

详细说明我的评论,这是一个python示例:

elaborating on my comment, here is a python example:

 fortrancode = """
       implicit none
       integer, parameter :: n=%i
       integer,parameter :: rp=selected_real_kind(n)
       write(*,*)n,rp
       end
 """
 from subprocess import call
 for n in range(-1,33):
  f=open('test.f','w')
  f.write(fortrancode%(n))  ! <- n here gets string substituted
                            !for the '%i' in fortrancode
  f.close()
   ! optional check  call(['grep','n=','test.f'])
  call(['gfortran','test.f','-o','test.exe'])
  call(['./test.exe'])
 -1 4
  0 4
  1 4
...
  7 8
...
 18 10
 19 -1
...
 32 -1

这篇关于定义一个必须声明为常量但在循环中更改的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:03