带有打印语句的整数输出格式 [英] Integer output formatting with print statement
问题描述
I've noted that if I use integer(16)
variables, when I use print
, the output contains the exact number of spaces expected. Thus, when I use (some might recognize a project euler problem here)
implicit none
integer(16)::sum_sq,sq_sum,diff,i
sum_sq=0;sq_sum=0;
do i=1,100
sum_sq=sum_sq+i*i
sq_sum=sq_sum+i
enddo
diff=abs(sq_sum**2-sum_sq)
print *, "The difference is", diff
I get
The difference is 25164150
as the output, but when I use integer(8)
or integer
for the variables, I get
The difference is 25164150
as the output. This occurs with and without the -m64
flag and only on gfortran (my ifort does not seem to accept kind=16
, a separate issue to be dealt with, but returns the output with the spaces for integer(8)
).
Does anyone know why this occurs?
As already answered, you are using list-directed IO, which while convenient, is not completely specified by the language standard. So you will find idiosyncrasies. If you want to control the output will need to use a format. Also convient is the format specifier "I0", which uses the minimum number of digits required to output the item.
As a side issue, "integer (N)" is not guaranteed to be an N-byte integer. It is not the same as "integer*N", which is not part of the language standard. Many compilers use for the kind values the number of bytes of the type, but there are exceptions. In hindsight, it was a mistake to use integer values to designate integer, real & logical sub-types. If you want to select types by the number of bytes, there are methods starting with Fortran 2003. The ISO_C_Binding module of Fortran 2003 provides type designators such as C_INT32_T, C_INT64_T and C_INT128_T. The ISO_FORTRAN_ENV module for Fortran 2008 provides INT8, INT16, INT32 and INT64.
这篇关于带有打印语句的整数输出格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!