为斐波那契数列创建表

  • 本文关键字:数列 创建 c
  • 更新时间 :
  • 英文 :


提前谢谢你。我感谢任何和所有的反馈。我是编程新手,我正在做一项任务,根据用户要求的数字数量打印斐波那契数列。我已经完成了大部分代码,但还有一段我有困难。我希望我的输出以表格格式出现,但我的代码有些问题,我没有在输出中获得我想要的所有数据。灰色是我的代码、我的输出和我想要的输出。

#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 ntt Fibonacci Numbersn");
printf(" %d ttt%dn ttt%dn ", sequence, a, b);
for (i=0; i <= (n - 3); i++)
{
    c = a + b;
    a = b;
    b = c;
    sequence++;
    printf("ttt%dn ", 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

我没有获得所有数据

  • 这是因为您没有在for循环printf()打印sequence

    printf("ttt%dn ", c);
    
  • 甚至在循环之前的第二个数字之前for

    printf(" %d ttt%dn ttt%dn ", sequence, a, b);
    

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

printf(" %d ttt%dn %dttt%dn ", 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("%dttt%dn ",++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 ntt Fibonacci Numbersn");
    printf(" %d ttt%dn %dttt%dn ", sequence, a, sequence+1, b);
    sequence++;
    for (i=0; i <= (n - 2); i++)
    {
        c = a + b;
        a = b;
        b = c;
        printf("%dttt%dn ",++sequence, c);
    }
}
int main()
{
int n;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
fib(n);
return 0;
}

您忘记在 for 循环中打印sequence。在给出适当的t数后,在 for 循环中打印sequencec

这将起作用,最好正确缩进您的代码:

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 nttFibonacci Numbersn");
    printf(" %dttt%dn", sequence, a);
    printf(" %dttt%dn", ++sequence, b); //   <- and you can use pre increment operator like this for your purpose
    for (i=0; i <= (n - 3); i++) {
        c = a + b;
        a = b;
        b = c;
        sequence++;
        printf(" %dttt%dn",sequence, c);
    }
    return 0;
}

输出:

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

最新更新