gpt4 book ai didi

c++ - 二维数组不会在控制台网格中显示正确的内容

转载 作者:搜寻专家 更新时间:2023-10-31 01:00:44 24 4
gpt4 key购买 nike

我正在使用 C++ 开发一个简单的基于文本的 Battle Ship 游戏。我目前正在尝试在控制台中正确显示网格/板。我的格式正确,但我发现二维数组的元素不正确。下面是一个例子。 我已将二维网格中的所有元素设置为 Z,但出于某种原因它们都显示为 Y。为什么要更改变量?

#include <iostream>
using namespace std;

enum Grid {X, Y, Z};

const int GRID_SIZE = 10;
Grid grid[GRID_SIZE][GRID_SIZE] = {Z};

void displayGrid();

int main()
{
displayGrid();
cin.get();
return 0;
}

void displayGrid()
{
// Display top column of the grid, containing numbers.
cout << "\t |";
for (int i = 0; i < GRID_SIZE; i++)
cout << i << "|";
cout << endl;

Grid gridContent;

for (int y = 0; y < GRID_SIZE; y++)
{
cout << "\t" << y << "|";

for (int x = 0; x < GRID_SIZE; x++)
{
gridContent = grid[y][x];
if (gridContent = X)
cout << "X|";
else if (gridContent = Y)
cout << "Y|";
else if (gridContent = Z)
cout << "Z|";
}
cout << "\n";
}
}

最佳答案

第一:

Grid grid[GRID_SIZE][GRID_SIZE] = {Z}

只初始化数组的第一个元素gridZ (其余元素为 0,参见 aggregate initialization )。您需要在 main 中嵌套循环将所有元素初始化为Z , 喜欢

for(int i = 0; i < GRID_SIZE; ++i)
for(int j = 0; j < GRID_SIZE; ++j)
grid[i][j] = Z;

第二:

if (gridContent = X) 

设置gridContentX (此错误也发生在其他 if 中)。要测试相等性,需要使用 ==相反。

第三:如果你真的想明白为什么Y之前显示过,那是因为

中的条件
if(gridContent = X) 

计算为 false , 自 X转换为 0 ,然后分配给 gridContent .因此,程序进入其他

if(gridContent = Y)

在其中设置 gridContentY ,并且因为后者是非零的,所以 if条件评估为 true .您在循环中执行此操作,因此最终将所有元素显示为 Y .不完全是您想要的。


最佳实践

  • 避免这些错误的一种方法是在打开所有警告的情况下进行编译。例如,g++ -Wall -Wextra test.cpp吐出来

    warning: suggest parentheses around assignment used as truth value [-Wparentheses]

            if (gridContent = X)

    clang++ 更有用

    warning: using the result of an assignment as a condition without parentheses [-Wparentheses]

    所以你肯定知道出了什么问题。

  • 另一种方法是始终将 rvalue在等式测试的左边,比如

    if(X == gridContent)

    在这里X是一个右值,如果你输入错误 =相反 == ,那么编译器会报错,比如

    error: lvalue required as left operand of assignment

    因为您不能分配给右值。

  • 最后,尝试使用标准容器而不是原始数组,例如 std::vector<> .

关于c++ - 二维数组不会在控制台网格中显示正确的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386527/

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