重置c中变量的数量

时间:2016-11-02 21:42:24

标签: c

您好我正在尝试编写一个程序,可以评估一个数字是否在Fibonacci系列中:

  

(1 1 2 3 5 8 13 21 .....)

这是我的代码:

#include <stdio.h>
#include <conio.h>

main() {
    int received,n1,n2,n3,i;
    do {
        printf("Please enter a number to evaluate : ");
        n1=1;
        n2=1;
        i=0;    
        scanf("%d",&received);
        while(n3<received) {
            if (i==1) { 
                n1=1;
            }
            else {
                n3=n1+n2;
                n1=n2;
                n2=n3;
            }
            i++;
            printf("%4d \n",n1);
        }
        if(n1==received || n2==received || n3==received) {
            printf("True ! The number is in Fibonacci series \n");
        }
        else {
            printf("False ! The number is not in Fibonacci series \n");
        }
    }while(received>0);

    printf("Error occured !!!!!!!!!!!!!!!!!!!!!");
    getch();    
}

但是当我想重置变量的数量时,它不起作用:

n1=1;
n2=1;
i=0;

2 个答案:

答案 0 :(得分:1)

变量n3未初始化。测试while (i < received)第一次调用未定义的行为,程序在此之后的行为并不重要。

您可以通过从n3开始1当前斐波那契数字,然后使用您的公式逐步执行后续数字,来更正和简化代码。 0n1的初始值n2给出正确的序列。

另请注意,您应该检查scanf的返回值,并在使用输入0时退出循环。

以下是更正后的代码:

#include <stdio.h>
#include <conio.h>

int main(void) {
    int received, n1, n2, n3;
    for (;;) {
        printf("Please enter a number to evaluate : ");
        if (scanf("%d", &received) != 1)
            break;
        if (received <= 0)
            break;
        n1 = 0;
        n2 = 0;
        n3 = 1;    
        while (n3 < received) {
            n1 = n2;
            n2 = n3;
            n3 = n1 + n2;
            printf("%4d\n", n3);
        }
        if (n3 == received) {
            printf("True! The number is in Fibonacci series\n");
        } else {
            printf("False! The number is not in Fibonacci series\n");
        }
    }
    getch();    
}

答案 1 :(得分:-2)

我认为你的意思是我

#include <stdio.h>
#include <conio.h>
main()
{
int received,n1,n2,n3,i;
do
{
printf("Please enter a number to evaluate : ");
n1=1;
n2=1;
i=0;    
scanf("%d",&received);
 while(i<received)
 {
    if (i==1)
 {   
     n1=1;
  }else
 {
 n3=n1+n2;
 n1=n2;
 n2=n3;
 }
 i++;
 printf("%4d \n",n1) ;
 }
 if(n1==received || n2==received || n3==received)
 {
    printf("True ! The number is in Fibonacci series \n");
 }else
 {
    printf("False ! The number is not in Fibonacci series \n");
 }   
 }while(received>0);
printf("Error occured !!!!!!!!!!!!!!!!!!!!!");
getch();    
 }*

如果没有那么你需要初始化n3