Using C ++ rand () to get random directions (up / down / left / right) - always get up

I am making a C ++ text based Battleship game. I am using the rand () function to randomly place computers. I pick up the number generator once at the start of main () using the following line:

srand(static_cast<unsigned>(time(0)));

      

Later, I use the rand () function to select the locations where each individual ship will sail. (Coordinates where one end of the ship will begin). Then I use the rand () function in the function below, which determines the direction in which they will expand (depending on the length of the vessel):

char randDirection()
{
    int randNumber = rand();
    int x = (randNumber % 4) + 1;

    if (x = 1)
        return 'u';
    else if (x = 2)
        return 'd';
    else if (x = 3)
        return 'l';
    else
        return 'r';
}

      

It randomly takes a number between 1 and 4 and returns the direction (represented by char) depending on the number. While I have had success with randomly selecting the locations for the pieces , this function always sets the shapes vertically. They always rise. Can anyone tell me why?

+3


source to share


3 answers


Your problem is with every "if", you are executing an assignment, not a test. Moreover, in a test, assignment will always return assignment result. For example:



if (x = 0) // will never be here because 0 is false in a test else if (x = 42) // will always end up here else // will never be here

+4


source


Your problem seems to be in the statement x = 1

you should change to x == 1

because the assignment will always be true.



Hope for this help!

+6


source


Try this to avoid a typo ==

;-):

char randDirection()
{
    return "udlr"[rand() % 4];
};

      

+4


source







All Articles