目前我想做的是将剩余的 for 循环转换为递归函数。之前,我对 R1、R2 和 R3 有一个 for 循环,它将根据它们的值生成总支出。
例如
1 1 1 payout is 1
1 1 2 payout is 1
1 1 3 payout is 1
.......
3 3 3 payout is 3
我能够将第一个 for 循环 (R1) 转换为递归函数,并且我的代码仍然可以正常编译。我现在遇到的问题是将剩余的 for 循环(R2 和 R3)也转换为递归函数。我尝试将 R1 的格式复制到 R2 和 R3 上,但我遇到了声明问题,因为此时每个变量都在其自己的函数中。
我应该采取哪些步骤才能正确解决这个问题?
这是我当前使用递归函数 R1 的工作代码:
int totalFunc(int R1, int R2, int R3);
void loopR1(int R1, int upto);
int R2, R3 = 1;
int totalScore = 0;
int main()
{
loopR1(1, 3);
return 0;
}
void loopR1(int R1, int upto)
{
if (R1 <= upto){
for(R2 = 1; R2 <= 3; R2++){
for(R3 = 1; R3 <= 3; R3++){
printf( " %d %d %d Total Score is: %d\n\n", R1, R2, R3, totalFunc(R1,R2,R3));
}
}
loopR1(R1+1, upto);
}
}
int totalFunc(int R1, int R2, int R3)
{
int totalScore = R1;
if (R2 < R1){
totalScore += R2;
if (R3 < R2){
totalScore += (2*R3);
}
else{
if (R3 < R1){
totalScore += R3;
}
}
}
else{
if (R3 < R1){
totalScore += R3;
}
}
return totalScore;
}
编辑:
我添加了 R Sahu 建议的更正,但我现在遇到的问题是 R1 没有递增,程序崩溃而不是成功返回 0。我相信该错误与我粘贴的代码部分有关下面。
int totalFunc(int R1, int R2, int R3);
void loopR1(int R1, int upto);
void loopR2(int R1, int R2, int upto);
int R3;
int totalScore = 0;
int main()
{
loopR1(1, 3);
loopR2(1, 1, 3);
return 0;
}
最佳答案
下一级递归函数,我们称之为loopR2
,需要有R1
、R2
和一个参数最多
。
void loopR2(int R1, int R2, int upto)
{
if (R2 <= upto){
for(R3 = 1; R3 <= 3; R3++){
printf( " %d %d %d Total Score is: %d\n\n", R1, R2, R3, totalFunc(R1,R2,R3));
}
loopR2(R1, R2+1, upto);
}
}
void loopR1(int R1, int upto)
{
if (R1 <= upto){
loopR2(R1, 1, 3);
loopR1(R1+1, upto);
}
}
我将让您弄清楚如何实现loopR3
。
关于c - 如何将剩余的 for 循环更改为递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814599/