【问题标题】:Difficulty with an accumulator in a nested for loop嵌套 for 循环中的累加器困难
【发布时间】:2017-11-06 00:39:58
【问题描述】:

我是 C++ 的新手,我必须为匹配游戏编写代码,但检测匹配的函数有问题。 下面是我为尝试调试匹配功能而制作的游戏的一个更简单的淡化版本。 基本上我有一堆数字存储在二维数组中,我需要循环遍历网格以查看是否有任何匹配项(一行中的 3 个相同字符,垂直或水平,构成匹配)。用户每场比赛获得一分。 每次匹配时,我都需要累积一个存储用户得分的变量。我认为代码非常直观,循环和 if 语句检查第 i 个元素之后的第二个和第三个元素,如果它们都相同,则检测到匹配。

我遇到的问题是点并没有被添加到计数变量中。 “事物”数组旨在模拟游戏板,我对其进行了设计,因此它至少有一个匹配项,而我的 if 语句似乎没有检测到。如何修复它以便“计数”存储积分?

我以前从未在这里发布过任何内容,因此对于格式有些混乱,我深表歉意,但这里是代码:

#include <iostream>
using namespace std;
int main() 
{
    int things[3][3] = {{3, 3, 3}, {2, 8, 4}, {3, 7, 2}};
    int count = 0; 
    for (int i = 0; i <= 3; i++)
    {
    for (int j = 0; j <= 3; j++)
    {
      if (things[i] == things[i+1])
        count++;
      if (things[i] == things[i+2])
        count++;
      if (things[i] == things[i+3])
        count++;
      else
      {
        if (things[j] == things[j+1])
          count++;
        if (things[j] == things[j+2])
          count++;
        if (things[j] == things[j+3])
          count++;
       }
     }
    }
    return 0;
}

【问题讨论】:

  • things[3][3] 数组的有效索引为 0 到 2。您允许 ij 运行高达 3,并进一步访问高达 i+3 和 @987654326 的索引@ - 超出范围。
  • things[i] == things[i+1] 比较指向ith 和i+1th 行的第一个元素的指针,而不是这些行中的值。指针当然永远不会相等;你的任何条件都不可能是真的。
  • 伊戈尔的观点都是准确的。此外,您的 i+1、i+2 和 i+3 的 if 语句始终运行,但您的 else 链接到 i+3。这意味着进行 j 检查的唯一时间是当 i+3 为假时。我还要解决这个问题,对于二维数组,您通常会索引两次,例如事情[i][j]

标签: c++ matching accumulator


【解决方案1】:

连续3个相同的字符,垂直或水平,构成匹配

代码太正确了你首先需要有正确的算法。

这就是我用伪代码编写它的方式:

For every row:
     - For first n-2 columns in this row
         - if current match result and next 2 match results are the same : increment counter

For every column:
     - For first n-2 rows in this column
         - if current match result and next 2 match results are the same : increment counter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多