我试图在嵌套的if语句中突破for循环。所以基本上我在做MasterMind游戏,我试着知道用户到底有多少正确的(漠不关心的位置)。所以基本上,我想出了把AI的二进制数字存储在一个数组中,然后比较每个用户的二进制数和它。当来自用户的二进制数字等于AI的一个二进制数时,它就应该跳出for循环。我是这样想的,我就这样想了:
void MasterMind::evaluateCorrection()
{
// AI : 1 1 1 0
//USER: 1 0 1 1
//Store AI In Array
int AI[3];
int count = 0;
std::copy(binaries.begin(), binaries.end(), AI);
for(std::vector<char>::iterator itAI= numbers.begin() ; itAI != numbers.end(); itAI++)
{
for(int i=0; i<=3;i++)
{
char numberAt = *itAI;
int intNumberAt = numberAt - '0';
if(intNumberAt = AI[i])
{
cout << intNumberAt << " VS " << AI[i] << endl;
actuallyCorrect++;
break;
}
}
}
cout << "\n ACTUALLY CORRECT " << actuallyCorrect << endl;
}
所以当我在bash中得到这个代码时:
BINARY :
1111
PLEASE ENTER A 4 DIGIT BINARY! OR PROGRAM WILL EXIT
1123
YOU HAVE 2 POSITIONS CORRECT
1 VS 1
1 VS 1
1 VS 1
1 VS 1
ACTUALLY CORRECT 4
这显然是不对的..。我输入了1123,上面说4实际上是正确的.其实只有两个是对的,1和1,请帮忙!
发布于 2016-05-15 03:53:46
AI[3]
超出了范围,所以当i=3
和数组的大小应该增加时,您不能访问i=3
。intNumberAt = AI[i]
是一项任务。使用==
操作符进行等式检查。试试这个:
void MasterMind::evaluateCorrection()
{
// AI : 1 1 1 0
//USER: 1 0 1 1
//Store AI In Array
int AI[4] = {0}; // initialize for in case what is copied has insufficient number of elements
int count = 0;
std::copy(binaries.begin(), binaries.end(), AI);
for(std::vector<char>::iterator itAI= numbers.begin() ; itAI != numbers.end(); itAI++)
{
for(int i=0; i<=3;i++)
{
char numberAt = *itAI;
int intNumberAt = numberAt - '0';
if(intNumberAt == AI[i])
{
cout << intNumberAt << " VS " << AI[i] << endl;
actuallyCorrect++;
break;
}
}
}
cout << "\n ACTUALLY CORRECT " << actuallyCorrect << endl;
}
https://stackoverflow.com/questions/37234357
复制相似问题