1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
/*
* Program chapter 6_6
*
* This program generates and prints ten random integers
* Between user specified limits.
*/
#include <cstdlib> // required for srand(), rand().
#include <iostream> // required for cin, cout.
using namespace std;
// Function prototype.
int rand_int(int a, int b);
int main() {
// Declare objects.
int seed;
char random_type, I, F;
// Get seed value and interval limits.
cout << "Enter a positive integer seed value: \n";
cin >> seed;
// Ask user "Do you want to generate integers or floats, enter I or F"
cout << "Do you want to generate integers (I) or floats (F)? Enter I or F: \n";
cin >> random_type;
// IF statement to check random_type
if (random_type == I) {
// Seed the random number generator.
unsigned int seed;
int a, b;
srand(seed);
cout << "Enter integer limits a and b (a<b): \n";
cin >> a >> b;
// Generate and print ten random numbers.
cout << "Random Numbers: \n";
for (int k = 1; k <= 10; ++k) {
cout << rand_int(a, b) << ' ';
}
cout << endl;
}
else if (random_type == F) {
// Ask user for float limits and accepts values for new float variable f1 and f2
float rand_float, a, b;
srand(seed);
cout << "Enter float limits f1 and f2: \n";
cin >> a >> b;
cout << "Random Numbers: \n";
for (double k = 1; k <= 10; ++k) {
cout << rand_float(a, b) << " ";
}
cout << endl;
}
// Exit program.
return 0;
}
/* This function generates a random integer
* between specified limits a and b (a<b).
*/
int rand_int(int a, int b) {
return rand() % (b - a + 1) + a;
}
double rand_float(double a, double b) {
return ((double)rand() / RAND_MAX) * (b - a) + a;
}
|