C++/Development/Random
Outputs 20 random numbers from 1 to 100.
<source lang="cpp">
- include <stdlib.h>
- include <iostream>
- include <iomanip>
using namespace std; int main() {
unsigned int i, seed; cout << "\nPlease type an integer between " "0 and 65535: "; cin >> seed; // Reads an integer. srand( seed); cout << "\n\n " "RANDOM NUMBERS\n\n"; for( i = 1 ; i <= 20 ; ++i) cout << setw(20) << i << ". random number = " << setw(3) << (rand() % 100 + 1) << endl; return 0;
}
</source>
Rand function
<source lang="cpp">
- include <iostream>
- include <cstdlib>
using namespace std; class Dice {
int val;
public:
void roll();
}; void Dice::roll() {
val = (rand() % 6) + 1; // generate 1 through 6 cout << val << endl;
} int main() {
Dice one, two; one.roll(); two.roll(); one.roll(); two.roll(); one.roll(); two.roll(); return 0;
}
</source>
Random by time
<source lang="cpp">
- include <iostream>
- include <ctime>
using namespace std; int main( void ) {
int i,j; srand( (unsigned)time( NULL ) ); /* Display 10 numbers. */ for( i = 0;i < 10;i++ ) { j= rand(); cout << j << endl; }
}
</source>