fortran90中整数的智能打印

发布于 2024-10-13 09:36:49 字数 706 浏览 8 评论 0原文

几年前简单介绍了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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪是无色的血 2024-10-20 09:36:49

使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文