Ryan Duval
Ryan Duval

Reputation: 1

2D array not populating correctly or...? C++

I have a serious problem that I just can't seem to solve. I apologize if it's a really newbie-like problem.

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;

For some reason, the output is always: FISH: 100 SHARKS: 0

I don't necessarily understand. Would someone be able to please help me? Thanks.

Upvotes: 0

Views: 90

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320371

= designates assignment operator in C++. Which means that what you have here

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

uses assignment operator inside if conditions. By the above you override your entire grid with FISH values.

Equality comparison in C++ is performed by == operator. But you already know that, since you already use == in your num comparisons. Why are you using = in these grid comparisons then?

Upvotes: 3

Related Questions