用打印语句整数输出格式 [英] Integer output formatting with print statement

查看:126
本文介绍了用打印语句整数输出格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到如果我使用 integer(16)变量,当我使用 print 时,输出包含预期空间的确切数量。因此,当我使用(有些人可能认识到一个项目欧拉问题在这里)

隐式无
整数(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 *,区别在于,diff

我得到

 区别是25164150 

作为输出,但是当我为变量使用 integer(8) integer 时,我得到

 区别是25164150 



作为输出。这发生在 -m64 标志处,并且仅在gfortran(我的ifort似乎不接受 kind = 16 ,这是另一个需要处理的问题,但是返回的结果是 integer(8))的空格。

有人知道为什么会发生这种情况吗?

解决方案

正如已经回答的那样,您正在使用列表控制的IO,没有完全由语言标准规定。所以你会发现特质。如果你想控制输出将需要使用一种格式。另外一个方便的是格式说明符I0,它使用输出该项目所需的最小位数。



作为一个问题,integer(N)是不保证是一个N字节的整数。它与integer * N不同,它不是语言标准的一部分。许多编译器使用类型值来表示类型的字节数,但也有例外。事后看来,使用整数值来指定整数,实数和整数是个错误。逻辑子类型。如果要按字节数选择类型,则会有一些以Fortran 2003开头的方法。Fortran 2003的ISO_C_Binding模块提供了类型标识符,例如C_INT32_T,C_INT64_T和C_INT128_T。 Fortran 2008的ISO_FORTRAN_ENV模块提供了INT8,INT16,INT32和INT64。


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆