How can I assign a number or value of variable into a character in Fortran77/90

夙愿已清 提交于 2019-12-19 10:04:53

问题


Suppose, I'm using a real variable x. I want to assign as a character so that I can use it for printing different filenames depending on the values of x in a do-loop.

My present code is:

      program test_print
      real*8:: x
      character*40:: chr_x

      x=1.d0

      do i=1,6
        write(chr_x,*) x
        open (unit=10, file="test_x_"//trim(adjustl(chr_x))//".dat")
        write(10,*)i,x      

         x=x+0.2d0 ! Update x
        close(10)   
      end do        


      stop
      end program test_print

Now this generates files with filenames:

test_x_1.0000000000000000.dat test_x_1.3999999999999999.dat test_x_1.7999999999999998.dat
test_x_1.2000000000000000.dat test_x_1.5999999999999999.dat test_x_1.9999999999999998.dat

whereas I want to have filenames:

test_x_1.000.dat test_x_1.399.dat test_x_1.799.dat
test_x_1.200.dat test_x_1.599.dat test_x_1.999.dat

Any help?


回答1:


Use an explicit format, something like

write(chr_x,'(f8.3)') x

(or even f0.3, but that is IIRC Fortran 95), or if you do not want rounding

open (unit=10, file="test_x_"//chr_x(2:6)//".dat")

instead.



来源:https://stackoverflow.com/questions/20033479/how-can-i-assign-a-number-or-value-of-variable-into-a-character-in-fortran77-90

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!