How can I assign a number or value of variable int

2020-03-26 07:21发布

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条回答
迷人小祖宗
2楼-- · 2020-03-26 08:02

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.

查看更多
登录 后发表回答