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

#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

最佳答案

我没有得到所有数据



那是因为您没有在sequence循环的printf()中打印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;
}

关于c - 创建斐波那契数列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37761561/

10-11 16:48