Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Fortran 串联两个整数_Fortran_Concatenation_Integer - Fatal编程技术网

Fortran 串联两个整数

Fortran 串联两个整数,fortran,concatenation,integer,Fortran,Concatenation,Integer,在Fortran中,将两个整数连接成一个整数的最佳方法是什么 integer a = 999 integer b = 1111 整数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(

在Fortran中,将两个整数连接成一个整数的最佳方法是什么

integer a = 999
integer b = 1111
整数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
编辑:请注意,此示例适用于任何整数长度,假设它们适合各自的
类型(无整数溢出)。

您最好使用将两个整数转换为一个字符,然后将其转换回整数

没有将数值转换为字符/字符串表示的内在过程。有关更多信息,请参阅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

如果您希望整数的字符表示具有不同的宽度,则必须更改格式字符串。

您可以使用数字顺序的信息:

integer :: a = 999
integer :: b = 1111

integer :: c

c = a * 10**(ceiling(log10(real(b)))) + b

write(*,*) c

“write(c,*)temp”行与您的想法不符。它将temp写入一个值为整数c的I/O单元,而不是写入c本身。相反,您需要从temp读取c。这是我的部件上的一个错误键入-从上面的行复制和粘贴。谢谢你指出,没问题。出于好奇,我用ifort、pgf90和gfortran尝试了你的代码。奇怪的是,ifort12似乎将temp写入整数c并打印出来,这不是预期/期望的行为。pgf90和gfortran的行为符合预期,生成fort.gibberish文件作为输出。我想你是指我以前的错误代码吧?我刚刚用cygwin下的gfortran试过,它还把temp写入一个整数并打印出来,这很奇怪。是的,我指的是前面的代码。不过,我总是喜欢在编译器中发现bug。