C斐波那契用户输入

时间:2016-03-27 02:02:42

标签: c loops fibonacci

我试图计算用户输入的斐波那契序列。因此,如果用户输入10,程序将输出序列中的所有数字,最多10个,在这种情况下为0,1,1,2,3,5,8

这是我的代码:

#include <stdio.h>
int main ()
{
    /* variable definition: */
    int a, b, usrNumber;
    /* Initialize */
    a = 0;
    b = 1;
    usrNumber = 0;
    /* Ask user for number */
    printf("Please enter a positive number\n");
    scanf("%d", &usrNumber);
    /* Conduct Loop */
    while (b < usrNumber)
    {
        printf("%d \n",a);
        a += b;
        printf("%d \n",b);
        b += a;
    }
    return(0);
}

当我将它运行10和60时,序列会停止一个短于预期的数字。当我运行90或300时,序列按预期工作。有关为什么我不能让较低的数字工作的任何想法?

4 个答案:

答案 0 :(得分:1)

将循环更改为:

#! python3

def edit_operations(first,second):
    a = list(first)
    b = list(second)
    counter = 0

    while a != b:
        if a[counter] != b[counter]:
            if len(a) > len(b):
                print("delete", counter + 1, a[counter])
                del a[counter]
            elif len(b) > len(a):
                print("insert", counter + 1, b[counter])
                a.insert(counter, b[counter])
            else:
                print("replace", counter + 1, b[counter])
                a[counter] = b[counter]
        else:
            counter += 1
    print("".join(a))

if __name__ == "__main__":
    edit_operations("Reperatur","Reparatur")
    edit_operations("Singel","Single")
    edit_operations("Krach","Stall")
    edit_operations("wiederspiegeln","widerspiegeln")
    edit_operations("wiederspiglen","widerspiegeln")
    edit_operations("Babies","Babys")
    edit_operations("Babs","Babys")
    edit_operations("Babeeees","Babys")

如果用户输入10,那么在第三次循环结束时,while (a < usrNumber) { printf("%d ", a); if (b < usrNumber) { printf("%d ", b); } a = a + b; b = b + a; } 为8,a为13.因为b大于10,循环停止,b即使它小于10

也不会被打印

答案 1 :(得分:1)

您可以使用辅助变量

,而不是每个循环执行两个步骤
while (b < usrNumber) { 
  aux=b;
  b+=a;
  a=aux;
  printf("%d ",b);} 

答案 2 :(得分:0)

我暂时没有使用过C,所以下面的代码可能需要稍微修改一下,但在我看来,使用递归函数会对Fibonacci序列更有意义:

    int GetFibonacciSequence(int index, bool printOutput)
    {
        int ret = 0;
        //Root of the function
        if (index == 0 || index == 1)
        {
            ret = index;
        }
        //Recursive portion
        else
        {
            int a = GetFibonacciSequence(index - 2, false);
            int b = GetFibonacciSequence(index - 1, printOutput);
            ret = (a + b);
        }
        //Output
        if (printOutput)
        {
            printf("%d ", ret);
        }
        return ret;
    }

答案 3 :(得分:0)

这是一种快速简便的方法。

int main(){
    int a=0, c=1, b=1, sum=0, lim;
    scan("%d", &lim);
    while (C < lim){ printf("%d. ",c); c=a+b; a=b; b=c; }
    return 0;
}