Fortran使用selected_real_kind统一精度时报kind参数为编译时常量错误如何解决
问题原因
报错核心是作用域问题:主程序中定义的dp参数仅在主程序内部生效,外部独立编写的vector_norm函数无法访问该参数,编译器处理函数内的real(dp)声明时,无法识别dp为合法的编译时常量,因此抛出错误。
解决方案(均保留selected_real_kind用法)
方案1:使用Module封装公共参数与函数(最推荐)
这是Fortran工程化代码的标准写法,统一管理的kind参数可以在所有引用该模块的代码单元中生效:
! 定义公共模块 module global_def implicit none integer, parameter :: dp=selected_real_kind(15) contains function vector_norm(n,vec) result(norm) integer, intent(in) :: n real(dp), intent(in) :: vec(n) real(dp) :: norm norm = sqrt(sum(vec**2)) end function vector_norm end module global_def ! 主程序引用模块 program main use global_def implicit none real(dp) :: v(9) v(:) = 3.14_dp print *, 'Vector norm = ', vector_norm(9,v) end program main
方案2:将函数放入主程序的contains段
适合单文件小型程序,函数会直接继承主程序作用域内的所有参数:
program main implicit none integer, parameter :: dp=selected_real_kind(15) real(dp) :: v(9) v(:) = 3.14_dp print *, 'Vector norm = ', vector_norm(9,v) contains function vector_norm(n,vec) result(norm) integer, intent(in) :: n real(dp), intent(in) :: vec(n) real(dp) :: norm norm = sqrt(sum(vec**2)) end function vector_norm end program main
两种方案都不需要把函数声明改成double precision function,完全保留selected_real_kind的可移植性优势。
内容的提问来源于stack exchange,提问作者Bayraktaroglu
相关产品推荐
相关产品推荐

