且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C中的Fibonacci序列产生负数?

更新时间:2022-02-06 23:41:08


我正在编写一个程序来为值生成Fibonacci序列最多1000位数。

I am writing a program to generate a Fibonacci sequence for values with up to 1000 digits.

不是你不是。您将值存储在 int 类型的变量中。通常这样的变量是32位值,并且最大可能值 2 ^ 31 - 1 。这相当于 2,147,483,647 ,这远远超过了达到1,000位数的目标。

Not yet you aren't. You are storing the values in variables of type int. Commonly such variables are 32 bit values and have a maximum possible value of 2^31 - 1. That equals 2,147,483,647 which is some way short of your goal of reaching 1,000 digits.

47 th 斐波纳契数是第一个超过 2,147,483,647 的数字。根据 Wolfram Alpha ,价值为 2,971,215,073

The 47th Fibonacci number is the first number to exceed 2,147,483,647. According to Wolfram Alpha, the value is 2,971,215,073.

当你的程序试图计算这样一个数字时,它会遇到整数溢出,因为真值不能存储在 INT 。您可以尝试准确分析溢出时发生的情况,为什么看到负值,但它确实不会让您走得太远。简单地说,你正在尝试的是 int

When your program attempts to calculate such a number it suffers from integer overflow, because the true value cannot be stored in an int. You could try to analyse exactly what happens when you overflow, why you see negative values, but it really doesn't get you very far. Simply put, what you are attempting is clearly impossible with int.

为了达到1,000位,你需要使用大整数类型。没有任何内置类型可以处理您想要处理的数字。

In order to reach 1,000 digits you need to use a big integer type. None of the built-in types can handle numbers as large as you intend to handle.