fortran90中整数的智能打印
几年前简单介绍了Fortran77之后,我开始学习Fortran90。在 Fortran 中打印整数时,必须指定要为打印整数保留多少个空格。考虑这个程序...
implicit none
integer :: i
i = 123
write(*, '(A, I3, A)') "'", i, "'" !3 spaces for output = no padding
write(*, '(A, I5, A)') "'", i, "'" !5 is too many, so output is padded
write(*, '(A, I2, A)') "'", i, "'" !2 is too few, so output is jibberish
write(*, '(A, I:, A)') "'", i, "'" !Default behavior
end program
...它生成以下输出。
'123'
' 123'
'**'
' 123'
当我不知道整数中有多少位时,如何为整数打印分配正确的空间量?
更新:如果您的编译器兼容 F95,您可以使用 I0
编辑描述符(即,输入 '(A, I0, A)'
对于上面示例中的 write
函数的第二个参数,谢谢@janneb!
I'm learning Fortran90 after a brief introduction to Fortran77 a few years ago. When printing integers in Fortran, you must specify how many spaces you want to reserve for printing the integer. Consider this program...
implicit none
integer :: i
i = 123
write(*, '(A, I3, A)') "'", i, "'" !3 spaces for output = no padding
write(*, '(A, I5, A)') "'", i, "'" !5 is too many, so output is padded
write(*, '(A, I2, A)') "'", i, "'" !2 is too few, so output is jibberish
write(*, '(A, I:, A)') "'", i, "'" !Default behavior
end program
...which generates the following output.
'123'
' 123'
'**'
' 123'
How do I allocate the correct amount of space for integer printing when I do not know how many digits are in the integer?
Update: If your compiler is F95-compliant, you can use the I0
edit descriptor (i.e., put '(A, I0, A)'
for the second argument of the write
function in my example above. Thanks @janneb!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 I0 编辑描述符。好吧,迂腐的 IIRC 是 Fortran 95,所以如果你真的严格要求不超过 F90,那么我想这行不通。
Use the I0 edit descriptor. Well, to be pedantic IIRC that is Fortran 95, so if you're really strict about no more than F90, then I suppose this won't work.