Fibonacci数的数量小于给定的n

时间:2016-03-01 18:47:27

标签: c count fibonacci

#include <stdio.h>

int fibonacci(int n) {
    int count, n1 = 0, n2 = 1, fib = 0;
    printf("Given number: ");
    scanf("%d", &n);
    count = 0;
    while (count < n) {
        fib = n1 + n2;
        n1 = n2;
        n2 = fib;
        ++count;
        if (n > fib)
            printf("%d ", fib);
    }
    return 0;
}

int main() {
    int szam;
    fibonacci(szam);
    return 0;
}

我已经走到这一步,我只是不知道如何计算这些数字。 例如:
输入:10
输出:1 2 3 5 8

但它应该是:
在:10
出:5

2 个答案:

答案 0 :(得分:0)

代码中的停止条件不正确:在计算了n斐波纳契数后,您停止了,而不是在计算出大于n的斐波纳契数时停止。

以下是更正后的版本:

#include <stdio.h>
int count_fibonacci(unsigned long long int n) {
    int count = 0;
    unsigned long long n1 = 1, n2 = 1, fib = 1;
    while (fib < n) {
        count++;
        fib = n1 + n2;
        n1 = n2;
        n2 = fib;
    }
    return count;
}

int main(void) {
    unsigned long long n = 0;
    printf("Given number: ");
    scanf("%llu", &n);
    printf("%d\n", count_fibonacci(n));
    return 0;
}

它为5的输入打印10,因为您的斐波纳契序列为:1 2 3 5 8...

但标准序列通常定义为1 1 2 3 5 8...,它应该返回6。您可以通过将初始状态更改为n1 = 0, n2 = 1, fib = 1来获得此行为。

答案 1 :(得分:0)

添加了计算Fibonacci数字的变量 fib_count (未对此进行测试......)

#include <stdio.h>

int fibonacci(int n)
{
  int n1=0, n2=1, fib=0, fib_count;
  printf("Given number: ");
  scanf("%d",&n);
  fib_count = 0;
  while (fib<n)
  {`

      fib=n1+n2;
      n1=n2;
      n2=fib;
      fib_count += 1;
      printf("%d ",fib);

  }
  printf("Fibonacci numbers smaller than %d : %d ",n, fib_count);
  return 0;
}

int main(){
int szam;
fibonacci(szam);
return 0;
}