在Fortran中,将两个整数连接成一个整数的最佳方法是什么?
integer a = 999
integer b = 1111
integer c
应该是 9991111
谢谢, SM。
integer a = 999
integer b = 1111
integer c
应该是 9991111
谢谢, SM。
integer :: a,b,c
character(len=99) :: char_a,char_b,char_c
a = 999
b = 1111
write(unit=char_a,fmt=*)a
write(unit=char_b,fmt=*)b
char_c = trim(adjustl(char_a))//trim(adjustl(char_b))
read(unit=char_c,fmt=*)c
print*,c
end
编辑:请注意,此示例适用于任何整数长度,假设它们适合其各自的kind
(没有整数溢出)。
您可以使用数字的顺序信息:
integer :: a = 999
integer :: b = 1111
integer :: c
c = a * 10**(ceiling(log10(real(b)))) + b
write(*,*) c
你最好使用内部文件将你的两个整数转换为字符,然后再将其转换回整数。
没有将数字值转换为字符/字符串表示的固有程序。请参阅Fortran Wiki上关于此主题的讨论以获取更多信息(请参见标题为“注意事项”的部分)。
例如,在你的情况下,你可以使用以下方法:
program test_conversion
implicit none
integer :: a=999
integer :: b=1111
integer :: c
character(len=7) :: temp
write(temp, '(i3.3, i4.4)') a, b ! You may need to change these format specifiers
read(temp, *) c
print*, c ! This prints 9991111
end program test_conversion
如果您想要不同宽度的整数字符表示,您将需要更改格式字符串。