数据结构——栈与递归(recursion)

/* recursion.c */
/* 递归 */

#include <stdio.h>

void interface(void);
/* 斐波那契数列以及阶乘函数声明 */
long long factorial(int n);
void fibonacci(int x, int y, int stop);

int main(){
    int flag, number;

    interface();
    for(;;){
        printf("Command: ");
        scanf("%d", &flag);
        switch(flag){
            case 0: puts("Bye!"); return 0; break;
            case 1:
                printf("Enter a number: ");
                scanf("%d", &number);
                if(number<=0)
                    printf("No negative factorial!\n");
                else
                    printf("%d! = %lld\n", number, factorial(number));
                break;
            case 2:
                printf("Enter a number: ");
                scanf("%d", &number);
                if(number<=0)
                    printf("No negative fibonacci!\n");
                else
                    fibonacci(1, 1, number);
                break;
        }
    }

    return 0;
}

void interface(void){
    puts("+******************+");
    puts("+  0, quit         +");
    puts("+  1, factorial    +");
    puts("+  2, fibonacci    +");
    puts("+******************+");
}
/* 函数实现 */
long long factorial(int n){
    /* 基线条件以及递归条件 */
    if(n==1)
        return 1;
    else
        return factorial(n-1) * n;
}
void fibonacci(int x, int y, int stop){
    if(x>stop){
        printf("\n");
    }else{
        printf("%d ", x);
        int tmp = y; y = x + y; x = tmp;
        fibonacci(x, y, stop); 
    }
}

 

posted @ 2019-09-09 15:59  no樂on  阅读(268)  评论(0编辑  收藏  举报