C 我正在为斐波那契级数编写代码,在级数的第44项之后,我开始在级数中得到负值,我不';我不知道为什么?

C 我正在为斐波那契级数编写代码,在级数的第44项之后,我开始在级数中得到负值,我不';我不知道为什么?,c,C,“我正在为斐波那契级数编写代码,在级数的第44项之后,我开始在级数中得到负值,为什么 #include <stdio.h> int main(void) { int i, n , t1 = 0 ,t2 = 1 ,next; printf("Enter the number of terms for series:"); scanf("%d", &n); while(i<=n){ next = t1 +t2 ; t1 = t2; t

“我正在为斐波那契级数编写代码,在级数的第44项之后,我开始在级数中得到负值,为什么

#include <stdio.h>
int main(void)
{
  int i, n , t1 = 0 ,t2 = 1 ,next;
  printf("Enter the number of terms for series:");
  scanf("%d", &n);
  while(i<=n){
    next = t1 +t2 ;
    t1 = t2;
    t2 = next;
    printf("%d\n", next);
    i++;
  }
  return 0;
}
#包括
内部主(空)
{
int i,n,t1=0,t2=1,next;
printf(“输入系列的术语编号:”);
scanf(“%d”和“&n”);

虽然我没有测试这个程序,但我想我知道答案

数字往往会很快变大。44已经是一个很大的数字。(例如,您可以使用调试器查看发生了什么。)

很可能“int”不够大,无法容纳该数字,因此会发生一些意想不到的事情

尝试修改您的程序以使用64位变量(“long-long”)。情况会发生变化。即使“unsigned int”也会给您一些额外的空间,但不会太多


其他提示:

  • 用“for”代替“while”,因为这是你的真实意图
  • 在使用变量之前初始化变量是一种很好的做法。在初始化变量之前使用“i”和“next”

  • 你得到负值是因为斐波那契级数的第45个元素超过了整数可以达到的最大值。(2147 483 647)

    任何一本好书都应该解释数字范围之类的事情。如果你的书没有涵盖这一点,那么我真的建议你找一本更好的书。