问题
I want to generate Fibonacci series in C. My code is giving a compilation error. Here is the code, Actually I am a beginner in programming.
main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
}
回答1:
This works well.
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
回答2:
This code will print the first 5 fibonnacci numbers
#include<stdio.h>
void main()
{
int first,second,next,i,n;
first=0;
second=1;
n=5;
printf("\n%d\n%d",first,second);
for(i=0;i<n;i++)
{
next=first+second;//sum of numbers
first=second;
second=next;
printf("\n%d",next);
}
}
回答3:
#include<stdio.h>// header files
#include<conio.h>
void main()
{
int f1=0,f2=1,f,n,i;
printf("enter the no of terms");
scanf("%d",&n);
printf("the fibbonacci series:\n");
printf("%d\n%d",f1,f2);
for(i=2;i<n;i++)
{
f=f1+f2;
f1=f2;
f2=f;
printf("%d\n",f);
}
}
回答4:
This will work for all the values of n.
void fibSeries(int n)
{
int first = 0, next = 1, index= 0;
if(n <= 0)
return;
if(n == 1)
printf("%d ", first);
else
{
printf("%d %d ", first, next);
if(n > 2)
{
while(index++ < (n-2))
{
int temp = first + next;
first = next;
next = temp;
printf("%d ", next);
}
}
}
}
回答5:
void main()
{
int a,b,c;
a = 0;
b = 1 ;
c = a + b;
printf(" %d ",a);
printf(" %d ",b);
while ( c <= 100)
{
printf(" %d ",c);
a = b;
b = c;
c = a + b;
}
}
回答6:
Code for Java
public class NewClass {
public void Fibonacci_Series(int input)
{
int a=0;
int b=1;
for(int i=1;i<=input;i++)
{
if(input==1){
System.out.println(a);
break; }
else if(input==2){
System.out.println(+a);
System.out.println(+b);
break; }
else if (input>2){
int c,sum=a+b;
System.out.println(sum);
a=b;
b=sum; }
}
}
}
来源:https://stackoverflow.com/questions/17229707/how-to-generate-fibonacci-series-in-c