作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
提前谢谢您。我感谢所有反馈。我是编程新手,我正在做一项作业,根据用户要求的数字数量打印斐波那契数列。我已经完成了大部分代码,但剩下的一段代码我遇到了困难。我希望以表格格式输出,但我的代码出现了问题,并且我没有在输出中获得我想要的所有数据。灰色是我的代码、我的输出和我想要的输出。
#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
最佳答案
I am not getting all of the data
这是因为您没有在 for
循环的 printf()
中打印序列
。
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;
}
关于为斐波那契数列创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37761561/
我是一名优秀的程序员,十分优秀!