gfortran - Is unspecified decimal length allowed for real output?

我只是一个虾纸丫 提交于 2019-12-12 22:08:22

问题


Is there a way to format a real number for output such that both the width and decimal parts are left unspecified? This is possible with ifort by just doing the following:

write (*, '(F)') num

...but I understand that that usage is a compiler-specific extension. Gfortran does accept the standard-compliant 0-width specifier, but I can't find anything in the standard nor in gfortran's documentation about how to leave the decimal part unspecified. The obvious guess is to just use 0 for that as well, but that yields a different result. For example, given this:

real :: num
num = 3.14159
write (*, '(F0.0)') num

...the output is just 3.. I know I could specify a decimal value greater than zero, but then I am liable to have undesired extra zeros printed.

What are my options? Do I have any?


回答1:


Best solution:

It turns out that the easiest solution is to use the g specifier ("g" for "generalized editing"). That accepts a 0 to mean unspecified/processor-dependent width, which is exactly what I wanted. This is preferable to leaving the entire format unspecified (write(*,*)) because you can still control other parts of the output, for example:

real :: num
character(len=10) :: word
num = 3.14159
word = 'pi = '
write (*, '(a5,g0)') word, num

yields this:

pi = 3.14159012

Thanks to Vladimir F for the idea (seen here).

Inferior alternative:

My first thought this morning after seeing High Performance Mark's answer was to write the real number to a character string and then use that:

character(len=20) :: cnum
write (cnum, *), num
write (*, '(a5,a)') word, trim(adjustl(cnum))

It yields the same output as the best solution, but it is a little more complicated and it doesn't offer quite as much control, but it gets close.




回答2:


You can always use list-directed output, that is

write(*,*) num

but this surrenders all control of num's format to the compiler which is allowed to choose any reasonable representation.

Your question makes clear some formatting options that you don't want, but is less forthcoming on a clear specification of how you want the output formatted.



来源:https://stackoverflow.com/questions/19503960/gfortran-is-unspecified-decimal-length-allowed-for-real-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!