例如,如果我做出这些定义:
Real, parameter :: No_01 = 2.34
Real, parameter :: No_02 = 34.56
我希望以这种方式用F
格式编写这些变量:
Character(*), parameter :: FMT_01 = '(2x,F4.2)'
Character(*), parameter :: FMT_02 = '(2x,F5.2)'
写入屏幕的结果将是:
Write(*, FMT_01 ) NO_01 => 2.34
Write(*, FMT_02 ) NO_02 => 34.56
是否有任何F
格式可用于确定编写结果:
结果是:
!Correct result !Not correct result
002.340 Something 2.340 Something
034.560 Something 34.560 Something
How to pad floating point output with leading zeros?的答案不适用,因为这些值可能是负数。
答案 0 :(得分:1)
如果您同时使用F0.2,那么您将获得:
2.34
34.56
这可以接受吗?
答案 1 :(得分:0)
对于不带前导零的常量字段宽度 ,您只需指定具有假定的最大字段宽度的格式。负号会自动处理,默认情况下会对值进行右调整。例如:
character(len=6) :: form
real :: rv1, rv2
! Format: floating point, field width=8 (includes the "."), decimal places=2
form = '(f8.2)'
rv1 = -12.34
rv2 = 123.45
write(*,form) rv1
write(*,form) rv2
! example output. notice the two leading spaces are just blanks, but the
! field width ("8") is constant and the ("2") decimal places are aligned:
-12.34
123.45
如果您希望字段宽度具有前导零,则必须使用您已经链接到的this SO answer中显示的技术,以及@agentp在评论中提出的诀窍。我无法判断你是否完全理解,所以这是一个展示这些想法的子程序:
subroutine leadingzeros(rv)
real, intent(in) :: rv
! local vars
character(len=11) :: form
if (int(rv)>0) then
form='(i4.4,f0.2)' ! allow a total of 4 leading zeros.
else
form='(i4.3,f0.2)' ! "-" sign takes up one space, so 3 leading zeros remain.
endif
! handle negative values as suggested by agentp
write(*,form) int(rv), abs(rv-int(rv))
end subroutine leadingzeros
现在,当您致电leadingzeros
时,输出如下:
! example output from 'call leadingzeros(rv1)'
-012.34
! example output from 'call leadingzeros(rv2)'
0123.45
答案 2 :(得分:0)
有两种方法可以从问题中获得结果:
Program Main
Implicit none
Open(15,File='Output.txt')
Write(15,'(1x,a,1x,"j",1x,a,1x,"Juhu!")') Writing_01(67.45),Writing_01(-4.04)
Write(15,'(1x,a,1x,"j",1x,a,1x,"Juhu!")') Writing_02(67.45),Writing_02(-4.04)
Close(15)
Contains
Function Writing_01 ( Deg ) Result ( Str )
Real,intent(in) :: Deg
Character(:),allocatable :: Str
Character(len = 15 ) :: Str_temp
If ( int( Deg ) > 0 ) then
Write(Str_temp , '(F0.2)' ) 100000.0 + Deg
Str_temp = Str_temp(2:)
Else
Write(Str_temp, '(F0.2)' ) 100000.0 + abs(Deg)
Str_temp = "-"//Str_temp(3:)
Endif
Str = trim ( adjustl ( Str_temp ))
End Function Writing_01
Function Writing_02 ( Deg ) Result ( Str_temp )
Real,intent(in) :: Deg
Character(:),allocatable :: Str_temp
Character(len=1561) :: Form_02 , Res
If (int( Deg ) > 0 ) then
Form_02 = '(i5.5,f0.2)' ! allow a total of 4 leading zeros.
Else
Form_02 = '(i5.4,f0.2)' ! "-" sign takes up one space, so 3 leading zeros remain.
Endif
Write(Res , Form_02 ) int( Deg ), abs( Deg - int( Deg ) )
Str_temp = trim ( adjustl ( Res ))
End Function Writing_02
End program Main