问题描述
- c语言。
-
Write a program to calculate the Fibonacci sequence? The i-th element of the Fibonacci sequence is defined as follows.公式请看图 Ex)011235813
Fibonacci sequence? Input 1, input another numberto calculate the Fibonacci sequence? Input 2, show the Fibonacci sequence ? Input 3, initialization? Input 4, terminate the program
解决方案
void PrintMenu()
{
printf("*************
");
printf("1. Calculate
");
printf("2. Show it!
");
printf("3. Initialize
");
printf("4. Quit
");
printf("*************
");
printf("Input : ");
}
int main()
{
char a;
int b = 0;
int i;
int Fx = 1;
int Fxx = 0;
while(true)
{
PrintMenu();
a = getchar();
getchar();
switch(a)
{
case '1':
printf("Input the number : ");
scanf("%d",&b);
getchar();
break;
case '2':
for(i=0;i<b;i++)
{
if(i == 0)
printf("%d ",Fxx);
else if(i == 1)
printf("%d ",Fx);
else
{
printf("%d ",Fx+Fxx);
int temp = Fx;
Fx += Fxx;
Fxx = temp;
}
}
printf("
");
Fx = 1;
Fxx = 0;
break;
case '3':
b = 0;
break;
case '4':
return 0;
}
}
return 0;
}
解决方案二:
C语言中通过函数指针实现回调函数(Callback Function)
====== 首先使用typedef定义回调函数类型?======?
typedef void (*event_cb_t)(const struct event *evt, void *userdata);上面的语句表示event_cb_t类型函数范围值类型为void类......
答案就在这里:C语言中的回调函数
解决方案三:
#include<stdio.h>
void printList()
{
printf("*************
");
printf("1. Calculate
");
printf("2. Show it!
");
printf("3. Initialize
");
printf("4. Quit
");
printf("*************
");
printf("Input : ");
}
void nOfFab(int n)
{
int f1 = 0;
int f2 = 1;
int count = 2;
int tmp = 0;
if(n <= 0){
printf("
");
return;
}
printf("0");
if(n == 1){
printf("
");
return;
}
printf(" 1");
if(n == 2){
printf("
");
return;
}
while(count < n){
tmp = f1;
f1 = f2;
f2 = f1 + tmp;
printf(" %d",f2);
count ++;
}
printf("
");
}
void main()
{
int count = 0;
int select = 0;
int flag = 0;
while(!flag){
printList();
scanf("%d",&select);
switch(select){
case 1:
printf("Input the number : ");
scanf("%d",&count);
break;
case 2:
nOfFab(count);
break;
case 3:
count = 0;
break;
case 4:
flag = 1;
break;
}
}
}
解决方案四:
我的代码比较简洁,求采纳!
#include<stdio.h>
int PrintMenu()
{
int a;
printf("*************
");
printf("1. Calculate
");
printf("2. Show it!
");
printf("3. Initialize
");
printf("4. Quit
");
printf("*************
");
printf("Input : ");
scanf("%d",&a);
return a;
}
int main(){
int n=0;
int i;
int f1,f2,list[300]={0};
while(1){
switch(PrintMenu())
{
case 1:
printf("Input the number : ");
scanf("%d",&n);
f1=f2=1;
for(i=1;i<=n;i++){
list[i]=f1;
f1+=f2;
list[++i]=f2;
f2+=f1;
}
break;
case 2:
for(i=0;i<n;i++)
printf("%d ",list[i]);
printf("
");
break;
case 3:
n=0;
break;
case 4:
return 0;
}
}
}
时间: 2024-10-22 00:04:49