我试图突破一个for循环,在一个嵌套的if语句中。所以基本上我正在做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实际上是正确的...实际上只有2实际上是1和1.请帮助!
答案 0 :(得分:1)
AI[3]
超出范围,因此在AI[i]
时不得访问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;
}