创建斐波那契数列表

无限循环

先感谢您。我感谢所有反馈。我是编程新手,正在从事一项根据用户要求的数字打印斐波那契数列的作业。我已经完成了大部分代码,但是剩下的一小部分我很难处理。我希望以表格式输出,但是代码有些问题,并且我没有在输出中获得所有想要的数据。灰色是我的代码,我的输出以及我想要的输出。

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i, n;
int sequence = 1;
int a = 0, b = 1, c = 0;

printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);

printf("\n n\t\t Fibonacci Numbers\n");

printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b);

for (i=0; i <= (n - 3); i++)
{
    c = a + b;
    a = b;
    b = c;
    sequence++;
    printf("\t\t\t%d\n ", c);
}
return 0;
}

Here is my output: 
How many Fibonacci numbers would you like to print?: 8

n        Fibonacci Numbers
1           0
            1
            1
            2
            3
            5
            8
            13

Here is my desired output: 
How many Fibonacci numbers would you like to print?: 8

 n       Fibonacci Numbers
 1          0
 2          1
 3          1
 4          2
 5          3
 6          5
 7          8
 8          13
切鲁比

我没有得到所有数据

  • 那是因为你没有打印sequenceprintf()的中for环。

    printf("\t\t\t%d\n ", c);
    
  • 甚至循环前的第二个数字之前for

    printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b);
    

尝试对您的代码进行以下更改:

printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b);

sequence++; //as you've printed 2 values already in above printf

for (i=0; i <= (n - 3); i++)
{
    c = a + b;
    a = b;
    b = c;
    printf("%d\t\t\t%d\n ",++sequence, c); 
 //or do sequence++ before printf as you did and just use sequence in printf
}

样本输入: 5

样本输出:

How many Fibonacci numbers would you like to print?: 5 
 n       Fibonacci Numbers
 1          0
 2          1
 3          1
 4          2
 5          3

编辑:您可以通过这种方式使用函数...几乎是同一件事:)

#include <stdio.h>

void fib(int n)
{
    int i,sequence=0,a=0,b=1,c=0;

    printf("\n n\t\t Fibonacci Numbers\n");

    printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b);

    sequence++;

    for (i=0; i <= (n - 2); i++)
    {
        c = a + b;
        a = b;
        b = c;
        printf("%d\t\t\t%d\n ",++sequence, c);
    }
}

int main()
{
int n;

printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
fib(n);

return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章