2D数组没有正确填充或......? C ++

时间:2013-10-15 02:02:25

标签: c++

我有一个严重的问题,我似乎无法解决。如果这是一个真正类似新手的问题我会道歉。

srand(117);
//enumeration type to keep track of which fish is which
enum CellState {EMPTY, FISH, SHARK};

//Creating the grid
CellState fishGrid[MAX_X][MAX_Y];
for(int m = 0; m < MAX_X; ++m)
{
    for(int n = 0; n < MAX_Y; ++n)
    {
        int num = rand() % 2;
        if(num == 0)
            fishGrid[m][n] = EMPTY;
        else
        {
            num = rand() % 2;
            if(num == 0)
                fishGrid[m][n] = SHARK;
            else
                fishGrid[m][n] = FISH;
        }
    }
}
//calculate how many on grid
if(stepsTaken % 5 == 0)
    {
        int fishAmount = 0;
        int sharkAmount = 0;

        for(int m = 0; m < MAX_X; m++)
        {
            for(int n = 0; n < MAX_Y; n++)
            {
                if(fishGrid[m][n] = FISH)
                    fishAmount++;
                else if(fishGrid[m][n] = SHARK)
                    sharkAmount++;
            }
        }
        cout << "FISH: " << fishAmount << endl
        << "SHARKS: " << sharkAmount << endl << endl;

由于某种原因,输出始终是: 鱼:100 鲨鱼:0

我不一定明白。有人能帮助我吗?感谢。

1 个答案:

答案 0 :(得分:3)

=在C ++中指定 assignment 运算符。这意味着你在这里拥有什么

            if(fishGrid[m][n] = FISH)
                fishAmount++;
            else if(fishGrid[m][n] = SHARK)
                sharkAmount++;

if条件中使用赋值运算符。通过上述内容,您可以使用FISH值覆盖整个网格。

C ++中的等式比较由==运算符执行。但您已经知道,因为您已经在==比较中使用了num。那么为什么在这些网格比较中使用=