我必须写一个关于斐波那契系列的节目。该计划应该有两个功能。一个用于读取用户输入的功能和一个用于打印斐波那契序列的功能以及打印了多少个数字(序列的长度)。此外,打印斐波那契序列的功能应该定义一个接受用户输入的参数。
有我的程序,请帮我检查一下,帮我完成剩下的程序:
#include <stdio.h>
#include <stdlib.h>
int Fibonacci(int);
int main()
{
int num;
printf("enter a number:\n");
scanf("%d",&num);
if (num < 0) {
printf("invalid user input, enter a positive number\n");
} else {
Fibonacci(num);
}
return 0;
}
int Fibonacci(int num)
{
int num1 = 0;
int num2 = 1;
int totalNum = 2;
int next;
printf ("%d,%d", num1, num2);
next = num1 + num2;
while (next <= num)
{
printf(",%d", next);
num1 = num2;
num2 = next;
next = num1 + num2;
}
}
答案 0 :(得分:0)
对于函数中打印的数量,只需要使用一个变量计数器并将其初始化为2(如预先计算的)counter=2
然后在循环中继续增加它
像这样的东西
fabonacci(....)
{
.
//rest of code
//
counter=2;
while (next <= num)
{
printf(",%d", next);
num1 = num2;
num2 = next;
next = num1 + num2;
++counter;
}
printf("\n%d\n",counter);
}