首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >释放一个for循环C++

释放一个for循环C++
EN

Stack Overflow用户
提问于 2016-05-15 03:47:27
回答 1查看 89关注 0票数 1

我试图在嵌套的if语句中突破for循环。所以基本上我在做MasterMind游戏,我试着知道用户到底有多少正确的(漠不关心的位置)。所以基本上,我想出了把AI的二进制数字存储在一个数组中,然后比较每个用户的二进制数和它。当来自用户的二进制数字等于AI的一个二进制数时,它就应该跳出for循环。我是这样想的,我就这样想了:

代码语言:javascript
运行
复制
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中得到这个代码时:

代码语言:javascript
运行
复制
 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,请帮忙!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-15 03:53:46

  • AI[3]超出了范围,所以当i=3和数组的大小应该增加时,您不能访问i=3
  • intNumberAt = AI[i]是一项任务。使用==操作符进行等式检查。

试试这个:

代码语言:javascript
运行
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37234357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档