且构网

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

Fib迭代Fibonacci算法给我一个错误的结果(47)

更新时间:2021-07-29 23:26:47

请注意,您在代码中使用的是类型为int的临时变量,而不是类型为long long int的临时变量.这意味着,如果要处理足够大的斐波那契数,将在代码中产生整数溢出.特别是,第47个斐波那契数是2,971,215,073,该数字太大而无法容纳带符号的32位整数,因此会出现溢出.

Notice that you are using temporary variables of type int in your code rather than type long long int. This means that if you get to the point where you're dealing with sufficiently large Fibonacci numbers, you'll get an integer overflow in your code. In particular, the 47th Fibonacci number is 2,971,215,073, which is too large to fit in a signed 32-bit integer, so you'll get an overflow.

更改临时变量的类型为long long int(或者更好的是,uint64_t)应该可以解决此问题.

Changing your temporary variables to type long long int (or, better yet, uint64_t) should fix this.