简体   繁体   English

用户输入的C斐波那契

[英]C fibonacci with a user input

Im trying to calculate the fibonacci sequence to a user input. 我正在尝试计算用户输入的斐波那契数列。 So if the user inputs 10 the program will output all of the numbers in the sequence up to 10 in this case its 0, 1, 1, 2, 3, 5, 8 因此,如果用户输入10,则程序将按顺序输出所有数字,最多10个,在这种情况下,其数字为0、1、1、2、3、5、8

Here is my code: 这是我的代码:

#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);
}

When I run it for 10, and 60 the sequence stops one number short then expected. 当我将其运行10和60时,序列会停止一个短的数字,然后是预期的数字。 When I run it for 90, or 300 the sequence works as expected. 当我运行90或300时,该序列按预期工作。 Any thoughts on why I can't get the lower numbers to work? 关于为什么我无法让较低的数字起作用的任何想法?

Change your loop to look like this: 更改循环,如下所示:

while (a < usrNumber)
{
    printf("%d ", a);
    if (b < usrNumber) { 
        printf("%d ", b);
    }
    a = a + b;
    b = b + a;
}

If the user inputs 10, then by the end of the third time your loop runs, a is 8 and b is 13. So because b is larger then 10, the loop stops and a doesn't get printed even though it is smaller then 10 如果用户输入10,则在循环运行第三次结束时, a为8, b为13。因此,由于b大于10,因此循环停止,即使a较小, a也不会被打印10

Instead of doing two steps per loop, you could use an auxiliar variable 您可以使用辅助变量来代替每个循环执行两个步骤

while (b < usrNumber) { 
  aux=b;
  b+=a;
  a=aux;
  printf("%d ",b);} 

I haven't used C in a while so the following code might need to be changed a bit, but it seems to me that using a recursive function would make more sense for the Fibonacci Sequence: 我已经有一段时间没有使用C了,因此以下代码可能需要更改一点,但是在我看来,使用递归函数对斐波那契序列更有意义:

    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;
    }

Here's a quick and easy way to do it. 这是一种快速简便的方法。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM