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?
source to share
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
source to share