【问题标题】:Recursive counter without a loop没有循环的递归计数器
【发布时间】:2014-12-05 08:15:33
【问题描述】:

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

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

我可以将它作为一个静态 int,但我不能将它作为一个 void。

谢谢!

【问题讨论】:

  • 你的错误是什么?你的问题不是很清楚...

标签: c++ recursion count void


【解决方案1】:

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

#include <iostream>
using namespace std;

void count(int x)
{
        if (x == 0)
        {
                return;
        }
        cout<<x<<endl;
        count(x-1);
}

int main()
{
        count(10);
}

【讨论】:

    【解决方案2】:

    如果您想从 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2015-06-09
      • 2020-05-30
      • 2010-10-21
      • 1970-01-01
      相关资源
      最近更新 更多