Generating different kinds of random things
#include <iostream> #include <limits> #include <stdlib.h> #include <time.h> #include <iomanip> #include <tgmath.h> #include <string> using namespace std; int main(int argc, const char * argv[]) { int dieFace = 0; const int MAX_FACE = 6; int randomIntMaxToMin = 0; const int RANDOM_THING_MAX = 7; const int RANDOM_THING_MIN = -3; const int NUMBER_OF_TESTS = 100; double randomDouble = 0; int colorNameNumber = 0; const int NUMBER_OF_COLORS_NAMES = 3; const int RED_NUMBER = 0; const int YELLOW_NUMBER = 1; const int GREEN_NUMBER = 2; const string RED_STRING = "RED"; const string YELLOW_STRING = "YELLOW"; const string GREEN_STRING = "GREEN"; const string NONE_STRING = "NONE"; string randomColorName = ""; srand(static_cast <unsigned int>(time(0))); // try the following line instead and run the program twice! // srand(42); // Same sequence of random numbers every time (nothing special about 42, just a particular sequence) cout << "Random values form a 6-sided die:" << endl; for (int i = 0; i < NUMBER_OF_TESTS; i++) { // Random roll of a 6 sided die dieFace = 1 + rand() % MAX_FACE; cout << dieFace << endl; } cout << endl; cout << "Random INT values between " << RANDOM_THING_MIN << " and " << RANDOM_THING_MAX <<":" << randomIntMaxToMin << endl; for (int i = 0; i < NUMBER_OF_TESTS; i++) { // some other random thing that is a random INT between some min and max randomIntMaxToMin = RANDOM_THING_MIN + rand() % (RANDOM_THING_MAX - RANDOM_THING_MIN + 1); cout << randomIntMaxToMin << endl; } cout << endl; cout << "Random DOUBLE values between " << RANDOM_THING_MIN << " and " << RANDOM_THING_MAX <<":" << randomIntMaxToMin << endl; for (int i = 0; i < NUMBER_OF_TESTS; i++) { // some other random thing that is a random DOUBLE between some min and max randomDouble = RANDOM_THING_MIN + ((RANDOM_THING_MAX - RANDOM_THING_MIN) * (rand() / (static_cast <double>(RAND_MAX)))); cout << randomDouble << endl; } cout << endl; cout << "Random color names: " << endl; for (int i = 0; i < NUMBER_OF_TESTS; i++) { // random colors: colorNameNumber = rand() % NUMBER_OF_COLORS_NAMES; switch (colorNameNumber) { case RED_NUMBER: randomColorName = RED_STRING; break; case YELLOW_NUMBER: randomColorName = YELLOW_STRING; break; case GREEN_NUMBER: randomColorName = GREEN_STRING; break; default: randomColorName = NONE_STRING; break; } cout << randomColorName << endl; } system("pause"); return 0; }Back to top