我试图编写一个在C中定义为参数的函数

时间:2015-10-17 08:16:31

标签: c

我必须写一个关于斐波那契系列的节目。该计划应该有两个功能。一个用于读取用户输入的功能和一个用于打印斐波那契序列的功能以及打印了多少个数字(序列的长度)。此外,打印斐波那契序列的功能应该定义一个接受用户输入的参数。

有我的程序,请帮我检查一下,帮我完成剩下的程序:

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

}
}

1 个答案:

答案 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);
 }