【发布时间】:2016-03-07 07:43:35
【问题描述】:
我的代码是当数组中的数字为 1 时 +1 得分,当数组中的数字为 -1 时得分 -1。但是当我运行程序时它只返回0。递归本身没有无限循环,我不知道我在这里做错了什么。
#include <iostream>
using namespace std;
/* When the tile is -1, score--. When the tile is 1, score++. You cannot go outside the array nor can you go backwards */
/* + 2 through the array */
int jumping( int track[], int size, int location ){
static int score = 0;
if ( track[ location ] == 1 ){
score++;
}
else if ( track[ location ] == -1 ){
score--;
}
if (( location == size - 1 ) || ( track[ location + 1 ] == 0 )){
return score;
}
else{
jumping( track, size, location + 2 );
}
}
/* Run through the array by 1 */
int stepping( int track[], int size, int location ){
static int score = 0;
if ( track[ location ] == 1 ){
score++;
}
else if ( track[ location ] == -1 ){
score--;
}
if ( location == size - 1 ){
return score;
}
else{
stepping( track, size, location++ );
}
}
/* Is to calculate the maxium possible score for any given track, with any arrangement using recursion. */
int maxScore( int track[], int size, int location ){
int score = 0; //Keep track of score
int step = stepping( track, size, location );//score by stepping
int jump = jumping( track, size, location );//score by jumping
/* If step is higher or jump and replace according to the highest */
if ( step > jump ){
score = step;
return score;
}
else if ( jump > step ){
score = jump;
return score;
}
else if ( jump == step ){
return score;
}
}
int main(){
int simple[2] = { 0, 0 };
int easy[8] = { 0, -1, 1, 1, -1, 1, -1, 0 };
int medium[25] = { 0, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 0 };
int mediumhard[3] = { 0, 1, 0 };
int impossible[20] = { 0, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 0 };
int insane[40] = { 0, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1,
1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 0 };
cout << "1. SIMPLE............................................... " << maxScore( simple, 2, 0 ) << endl;
cout << "2. EASY................................................. " << maxScore( easy, 8, 0 ) << endl;
cout << "3. MEDIUM............................................... " << maxScore( medium, 25, 0 ) << endl;
cout << "4. MEDIUM HARD.......................................... " << maxScore( mediumhard, 3, 0 ) << endl;
cout << "5. IMPOSSIBLE........................................... " << maxScore( impossible, 20, 0 ) << endl;
cout << "6. INSANE............................................... " << maxScore( insane, 40, 0 ) << endl;
return 0;
}
【问题讨论】:
-
您在条件 (
if (( location = size - 1 )...) 中有一个分配。这是故意的吗? -
另外,你可能想要
return stepping(track,size,location++),否则不会有明确的返回值 -
注意:赋值是在第二个 if 语句中以及在
stepping()中。if ( location = size - 1 ){ -
@Christian 这应该是在函数到达数组末尾时停止函数,而不是使用 if ( location
-
@RNar 好的,我会添加它并查看它的工作原理。
标签: c++ arrays loops if-statement recursion