c - 递归:如何保持 for 循环中不断变化的变量在递归期间不发生变化?
问题描述
我在递归函数中有一个 for 循环。每次 for 循环完成时,我的代码中的索引 i 都会更改,但是当递归开始时它会重置。是否可以通过另一个变量或类似的任何东西保存值?我需要一个变量来保持第一个递归步骤的“i”值(或者更确切地说是在任何递归开始之前我拥有的“i”值)。我的实际代码似乎相当复杂,所以我只是粘贴了一个示例代码来解释我的问题。
我尝试过使用其他变量,还有全局变量。不幸的是,每当递归发生时它们也会改变,因为我需要以某种方式将“i”值保存给它们。
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 循环时都会重置它。
解决方案
听起来您可能想将i
循环移出function
,然后将其传入。
例如,如果你有类似的东西:
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();
}
}
}
您可以将其更改为:
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
在这种情况下,可能有一个更好、更具描述性的名称。
推荐阅读
- twitch - 您如何找出 twitch 流媒体正在使用哪些扩展程序?
- vb.net - 在 VB.net 中拟合数据
- python - 我想在子目录中运行 python 文件
- javascript - 无法获取和更改子元素
- c - 如何获取存储在 C 中 char * 下的多字节字符的 unicode 值?
- autodesk-forge - 如何将输入(文本框、滑块等)添加到 Autodesk Forge 查看器
- windows - 使用 CURL Windows 发布 json
- regex - 文件中的 SED 替换
- c# - 如何在 c# 中使用 selenium sendkey 传递 url?
- python - 密集层的输入 0 与该层不兼容:输入形状的预期轴 -1 具有值 8192,但接收到的输入具有形状(无,61608)