User talk:Goofster1020

From WiiBrew
Jump to navigation Jump to search

Coding Tips Answers

How to get a random number and store it in a variable?

#include <stdlib.h>
...
int num;
num = rand();
...

That returns an integer between 0 and RAND_MAX (some large number, it's defined in a header file). To restrict the range between 0 and some positive integer, you can use the modulus operator, e.g.

num = rand() % 10; //range = 0 to 9 inclusive

--Michael 16:05, 21 March 2009 (UTC)

Thanks!!! --Goofster1020 01:16, 25 March 2009 (UTC)
Do you need help on the other questions? For those you just use libfat (fatInitDefault(), then normal fopen(), fread(), etc).--Michael 01:11, 8 April 2009 (UTC)
If you need a more random number use srand with it rand() (example):
#include <cstdlib> //Or <stdlib.h> for C.

srand((unsigned)time(0));  //Generates a random number.
int random = ( (rand() % 10));

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

This number will change if called for more than once, but only if called after the srand again. rand() generates a random number one time per variable per program. In other words srand is more random than rand(). Hope you understood that, as I'm a novice to coding as well.--TPAINROXX/BKW 02:08, 27 June 2009 (UTC)

Good info TPAINROXX. My understanding of srand() from the UNIX manual pages is that it sets the seed that rand() uses to calculate the next random number. Each time you call rand(), rand() returns a new random value. Internally, rand() remembers its state between calls, so you get the next random number from its internal random number generator.

What srand() does is allow the user to change rand()'s internal state. This is useful because the user can get repeatable random sequences by using the same seed (internal state). You can try this out by using a constant seed, and printing out the first 10 random numbers from rand(). The sequence should be the same each time you run your program.
--Michael 03:11, 27 June 2009 (UTC)

Program Ideas