没有循环的递归计数器

Recursive counter without a loop

本文关键字:递归 计数器 循环      更新时间:2023-10-16

我正在尝试在不使用循环的情况下编写以下代码的递归版本。

static void count (){   
    for ( int i =0; i <=10; i++) System.out.println(i);
}

我可以将其作为静态 int 来做,但我不能把它作为一个空。

谢谢!

我相信你想要一个递归函数来解决你的问题。

#include <iostream>
using namespace std;
void count(int x)
{
        if (x == 0)
        {
                return;
        }
        cout<<x<<endl;
        count(x-1);
}
int main()
{
        count(10);
}

如果你想从 0 到 10 计数,你可以用 2 个参数来完成:

#include <iostream>
using namespace std;
void count(int start, int end)
{
        if (start == end)
        {
                return;
        }
        cout << start << endl;
        count(++start, end);
}
int main()
{
        count(0, 10);
}