洛谷P1427 小鱼的数字游戏 题解 递归入门题

题目链接:https://www.luogu.com.cn/problem/P1427

题目大意:
给你一串数(输入到0为止),倒序输出这些数。

解题思路:

首先这道题目可以用数组存数据,然后输出。
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
int a[110], n;
int main() {
    while (~scanf("%d", &a[n]) && a[n]) n ++;
    for (int i = n-1; i >= 0; i --) {
        printf("%d", a[i]);
        if (i) putchar(' ');
    }
    return 0;
}

但是我们也可以不开数组来实现这个功能,那就是以递归的方式。
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
void f() {
    int a;
    cin >> a;
    if (a == 0) return;
    f();
    cout << a << " ";
}
int main() {
    f();
    return 0;
}
原文地址:https://www.cnblogs.com/quanjun/p/11987841.html