gpt4 book ai didi

c++ - 打破 for 循环 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:00:11 24 4
gpt4 key购买 nike

我试图在嵌套的 if 语句中跳出 for 循环。所以基本上我在做 MasterMind Game,我想知道用户实际走对了多少(舍弃位置)。所以基本上我想出了将 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。请帮助!

最佳答案

  • AI[3] 超出范围,因此当 i=3 时您不能访问 AI[i] 并且数组的大小应该增加。
  • 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;
}

关于c++ - 打破 for 循环 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37234357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com