Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.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_Fibonacci - Fatal编程技术网

Fortran 斐波那契数在某一项后变为负数

Fortran 斐波那契数在某一项后变为负数,fortran,fibonacci,Fortran,Fibonacci,我用Fortran编写了这个程序来显示第x项之前的斐波那契数: program fibonacci implicit none integer :: x,p,c,i,t !initializes limit, previous, current, iterative, and temp print *, "List the first x fibonacci numbers: " read *, x !reads the limit p=0 !sets previ

我用Fortran编写了这个程序来显示第x项之前的斐波那契数:

program fibonacci
implicit none
integer :: x,p,c,i,t !initializes limit, previous, current, iterative, and temp
print *, "List the first x fibonacci numbers: "
read *, x      !reads the limit
p=0            !sets previous to zero
c=1            !sets current to 1
do i=1,x
    print *, c !prints the current fibonacci number
t = c      !sets the temporary variable to the current
c = c + p  !sets the current to the current plus the previous
p = t      !sets the previous to the temporary value
end do         !iterates until it reaches the limit 'x'
end program fibonacci
当我编译并运行它,并输入数字10时,它会按预期运行

 List the first x fibonacci numbers: 
10
       1
       1
       2
       3
       5
       8
      13
      21
      34
      55
但当我进入50岁时:

 List the first x fibonacci numbers: 
50
       1
       1
       2
       3
       5
       8
      13
      21
      34
      55
      89
     144
     233
     377
     610
     987
    1597
    2584
    4181
    6765
   10946
   17711
   28657
   46368
   75025
  121393
  196418
  317811
  514229
  832040
 1346269
 2178309
 3524578
 5702887
 9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
1134903170
1836311903
-1323752223
512559680
-811192543
-298632863
我不知道问题是什么,据我所知,逻辑是合理的。我的错在哪里


我正在使用gfortran编译器。

我不是fortran专家,但我确实上过一次课

很明显,您使用的是一个四字节整数()。1836311903之后,您超过了最大整数值(2147483647),计算溢出


有两种方法可以更精确地计算斐波那契数。首先,您可以找到支持8或16字节整数的system/fortran编译器组合。至少在gfortran中的支持,似乎越来越少。另一种选择是使用多精度库,如。

您需要比普通的旧
整数更大的整数
——请参阅8字节整数就足够了,或者16字节整数通常可用。在挖掘多精度库之前,至少值得一试。