首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >递归:如何防止for循环中不断变化的变量在递归期间发生变化?

递归:如何防止for循环中不断变化的变量在递归期间发生变化?
EN

Stack Overflow用户
提问于 2019-01-17 03:24:34
回答 1查看 616关注 0票数 1

我在一个递归函数中有一个for循环。我的代码中的索引i在for循环每次完成时都会更改,但是在递归开始时它会重置。有没有可能通过另一个变量或类似的东西保存该值?我需要一个变量来保持第一个递归步骤的'i‘值(或者更确切地说,是我在任何递归开始之前拥有的'i’值)。我的实际代码看起来相当复杂,所以我只是粘贴了一个示例代码来解释我的问题。

我尝试过使用其他变量,也包括全局变量。不幸的是,每当递归发生时,它们也会发生变化,因为我需要以某种方式将'i‘值保存到它们中。

代码语言:javascript
复制
   int array[2][10];
   void function(){
      int x = 1;
      for (int i = 0; i < 10; i++){
         //Something happens here... (The base cases are in here)
         for (int j = 0; j < 10; j++){
            //Something happens here...(More base cases are in here)
            array[0][x] += i; //When function() starts, i is 0. I need it to 
                              //remain 0, while it
                              //runs through all the recursion steps (limited 
                              //by a recursion counter).
                              //After the recursion returns to the first level, 
                              //the for loop will continue.
                              //'i' will be 1 and then I need this value to 
                              //stay the same throughout all the
                              //recursion steps once again. How do I do that?
            //Recursion
            function();
         }
      }
   }

我希望'i‘保持不变,但是每次递归重新启动for循环时,它都会被重置。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-17 03:37:35

听起来您可能想要将i循环移出function,然后将其传递进来。

例如,如果你有这样的东西:

代码语言:javascript
复制
void someOtherFunction()
{
    function();
}
void function(){
  int x = 1;
  for (int i = 0; i < 10; i++){
     //Something happens here...
     for (int j = 0; j < 10; j++){
        //Something happens here...
        array[0][x] += i;
        //Recursion
        function();
     }
  }
}

您可以将其更改为:

代码语言:javascript
复制
void someOtherFunction()
{
    for (int i=0; i<10; ++i)
        function(i);
}
void function(int i){
  int x = 1;
 //Something happens here...
 for (int j = 0; j < 10; j++){
    //Something happens here...
    array[0][x] += i; 
    //Recursion
    function(i);
  }
}

在这种情况下,i可能有一个更好、更具描述性的名称。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54223966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档