Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

format - How to get rid of unwanted spacing in Fortran's print output?

It may look like a trivial issue, but I couldn't find any answer through googling. I have this little program :

Program Test_spacing_print
  Integer:: N
  Real:: A,B

  N=4; A=1.0; B=100.0

  print*,'N =',N

  print*,'A =',A,' B =',B
  print '(2(A3,F8.2,1X))' ,'A =',A,' B =',B
  print 20, A,B
  20 format('A =',F8.2,x,'B =',F8.2)

End Program Test_spacing_print

which gives me the output:

     N =           4
 A =   1.00000000      B =   100.000000
A =    1.00  B   100.00
A =    1.00 B =  100.00

I want to get rid of the unwanted space that I get after = sign, i.e. my desired output should look like (1 space after =):

 N = 4
 A = 1.00000000 B = 100.000000
 A = 1.00 B = 100.00
 A = 1.00 B = 100.00

Is it possible in fortran ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You say that you have "unwanted" space in the output, but you have exactly the space that you asked for with your specified explicit formats. When you didn't provide a format, list-directed output means that you have no say on the spacing.

To output A you have the edit descriptor F8.2: the field width will be 8. With two digits after the decimal point and the decimal point itself that leaves you with five digits for the digits (and sign) before the decimal point. So, for A value 1. without the optional sign printed you will have four blanks.

Much as Fortran 95 introduced the I0 edit descriptor so it allows F0.d. [And for other descriptors, although G0.d was added even later.] F0.2 will provide the minimal field width with those two digits after the decimal point, which is what you want. Note, though, that you will need to explicitly add a blank after the = sign:

print '("N = ", I0)', N
print '(2(A4,F0.2,:,1X))' ,'A = ',A,'B = ',B

[I've also used the : edit descriptor to avoid trailing blanks.]

If you want a truly Fortran 90 answer, as you've tagged, then it won't be as nice but it still can be done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...