如何在Fortran77/90中将数字或变量值分配给字符 [英] How can I assign a number or value of variable into a character in Fortran77/90

查看:182
本文介绍了如何在Fortran77/90中将数字或变量值分配给字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用的是实数变量x.我想指定为一个字符,以便可以根据do循环中x的值使用它来打印不同的文件名.

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.

我现在的代码是:

      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

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

我想拥有文件名:

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

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

推荐答案

使用显式格式,例如

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

(甚至是f0.3,但是就是IIRC Fortran 95),或者如果您不想舍入

(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")

相反.

这篇关于如何在Fortran77/90中将数字或变量值分配给字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆