提前谢谢你。我感谢任何反馈。我是编程新手,我正在编写一个根据用户要求的数字打印斐波纳契数列的作业。我有大部分代码完成,但还有一件我遇到困难的部分。我希望我的输出采用表格格式,但是我的代码中有些东西已关闭,而且我没有得到我想要输出的所有数据。灰色是我的代码,输出和我想要的输出。
#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
答案 0 :(得分:0)
您忘记在for循环中打印sequence
。在给出适当数量的sequence
之后,在for循环中打印c
和\t
!
答案 1 :(得分:0)
我没有收到所有数据
那是因为您没有在sequence
循环的printf()
中打印for
。
printf("\t\t\t%d\n ", c);
甚至在for
循环之前的 nd 号码之前
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;
}
答案 2 :(得分:0)
这样可行,也可以更好地缩进代码:
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\tFibonacci Numbers\n");
printf(" %d\t\t\t%d\n", sequence, a);
printf(" %d\t\t\t%d\n", ++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(" %d\t\t\t%d\n",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