PDA

View Full Version : rand()


kbum
09-08-2003, 01:01 PM
In this little program from my book, I didn't understand how

(1+rand()%6);

works. Can someone explain it to me please?


#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()
{
for(int counter=1;counter<=20;counter++)
{
cout << setw(10) << (1+rand()%6);

if(counter % 5 == 0)
cout << endl;
}

return 0;
}

jamessan
09-08-2003, 01:24 PM
rand() returns some pseudo-randomly generated number between 0 and MAX_INT, iirc. When you modulo that number by 6, you are dividing it by 6 and returning the remainder, which will be some number between 0 and 5. Then, 1 is added so that it is a number 1 through 6.

kbum
09-08-2003, 01:45 PM
Thanks. Another quick question :rolleyes:
I never know what data type to use when creating variables. The ones I use the most are int, for numbers like 1,2,3,4,-1,-2,-3,-4, etc, float for numbers like 3.24, 5.0, etc, and double, for numbers like 3.14159. I need some clarification on the following data types:

long double
unsigned long int
long int
unsigned int
unsigned short int
short in
unsigned char

Sorry if I'm bothering you :redfaced:

Thanks again.

kbum
09-08-2003, 08:00 PM
Nevermind.

bootyburglar
09-10-2003, 05:58 PM
hello, i saw somehting in your code that I dont have the time to reference;

code:
using namespace std;