gpt4 book ai didi

为斐波那契数列创建表

转载 作者:行者123 更新时间:2023-11-30 19:38:38 26 4
gpt4 key购买 nike

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

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com