+ 1
How would i go about re-generating a random number?
currently I'm generating a random number between 0 and 5 for my game by generating a seed(for example stand((unsigned)time(0)) and then declaring a variable with Rand()%5 , but unlike in python i can't just redeclare the variable to get a new random number. any advice? https://code.sololearn.com/c9tqInYzAB9Q/?ref=app
3 Antworten
0
Write a function that generates the random number
0
Pretty much your entire gen_num function is a big no-no
You only want to call srand once, but if you call this function multiple times that's not gonna fly. If the program calls this function multiple times per second you get the same value for time(0) and you get the same value every time.
Then you try to return twice, obviously that's not gonna work.
e_att will still be left without any value.
Just do something like this to get random numbers:
( even though I advice not to use rand() but it's good enough for beginners )
int generateNumber(int min, int max)
{
return min + rand() % ( max - min + 1 );
}
int main()
{
srand(time(nullptr)); // Only called once here.
int a = generateNumber(0, 5);
int b = generateNumber(121, 8231);
std::cout << a << " " << b << std::endl;
a = generateNumber(0, 5);
std::cout << a << " " << b << std::endl;
}
0
Include this header, then use random::pick_a_number(0, 5). Remember to use random::randomize() once the program starts to select a random seed.
https://code.sololearn.com/c9JJ5j9VxdD2/?ref=app