How to generate random numbers between 2 values, inclusive? [duplicate] - c++

This question already has answers here:
Generating a random integer from a range
(14 answers)
Closed 6 years ago.
I need help figuring out how to generate a set amount of random numbers between two user-inputted values, inclusively. Just so you know, I have searched for this but am not finding what I have just stated. Here is my code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int userBeg, userEnd, outPut;
cout << "Enter a start value: ";
cin >> userBeg;
cout << "Enter an end value: ";
cin >> userEnd;
srand(time(NULL)); //generates random seed val
for (int i = 0; i < 5; i++) {
//prints number between user input, inclusive
outPut = rand()%((userEnd - userBeg) + 1);
cout << outPut << " ";
}//end for
return 0;
}//end main
I'm confused with the output I get for the following ranges:
1-100 yield output numbers which fall in-between, but not including, the boundaries such as 50, 97, 24, 59, 22.
But, 10-20 yield numbers such as 1, 14, 6, 12, 13. Here, the output is outside of the boundaries as well as in-between them. What am I doing wrong?
Thank you in advance for your help!

Using the c++11 random library.
You could use std::default_random_engine (or any other random engine) with std::uniform_int_distribution.
The values you pass to std::uniform_int_distribution will be the lower and upper bounds of your random range.
e.g.
#include <iostream>
#include <random>
int main()
{
const int nrolls = 100;
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,9);
int p[nrolls]={};
for (int i=0; i<nrolls; ++i)
{
p[i] = distribution(generator);
}
std::cout << "uniform_int_distribution (0,9):" << '\n';
for (int i=0; i<nrolls; ++i)
{
std::cout << i << ": " << p[i] << '\n';
}
}
If you wish to seed the random engine, create it like.
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);

rand returns number between 0 and RAND_MAX. By taking modulo userEnd - userBeg + 1 the boundaries will be limited to 0 and userEnd - userBeg. If the random number should be within given boundaries, then userBeg should be added, so the calculus becomes
outPut = rand()%((userEnd - userBeg) + 1) + userBeg;

It's still experimental, but it is exactly what you want
http://en.cppreference.com/w/cpp/experimental/randint
#include <iostream>
#include <experimental/random>
int main()
{
int random_number = std::experimental::randint(100, 999);
std::cout << "random 3-digit number: " << random_number << '\n';
}
Edited: it's really random http://en.cppreference.com/w/cpp/numeric/random

For the rand to work you need to do:
#include <cstdlib>
int main() {
int Min = 103;
int Max = 113;
int Number = std::rand() % (Max + 1 - Min) + Min;
return 0;
}
I omitted the cin for clarity. (Max + 1 - Min) makes it inclusive. + Min sets the minimum value!
So stuffed into a function you may use:
int randint(int Min, int Max) {
return std::rand() % (Max + 1 - Min) + Min;
}
After testing it works with negative numbers as well as positive.
Sample outputs (with a loop and cout):
11-23
The number is: 13
The number is: 18
The number is: 14
The number is: 17
The number is: 18
The number is: 18
The number is: 23
The number is: 15
The number is: 11
The number is: 22
The number is: 22
The number is: 11
The number is: 22
The number is: 16
The number is: 14
The number is: 21
The number is: 16
The number is: 19
The number is: 15
The number is: 13
The number is: 17
1239-1242
The number is: 1240
The number is: 1242
The number is: 1239
The number is: 1241
The number is: 1241
The number is: 1241
The number is: 1239
The number is: 1240
The number is: 1240
The number is: 1240
The number is: 1242
The number is: 1240
The number is: 1242

Related

How to include a range in C++ guessing game and get code to repeat?

A simple guessing game, but I need instead of simply telling the user that their guess was too high or too low, modify the code such that the user is now given a range of numbers within which the chosen number actually lies.
Precisely,the user is shown a range [low, high] such that low ≤ num ≤ high.
At the beginning of the game, [low, high] = [0, 100], but as the user makes more guesses, the range is refined and a more accurate range is shown.
An example:
Suppose that num = 78. You first ask the user to make a guess between [0, 100].
The user enters 50 as their guess. So the next range would be [51, 100] since 51 ≤ 78 ≤ 100.
On the other hand, if the user had entered 90, then the next range would have been [0, 89].
Can someone also help me figure out how to get user input so that the code can repeat and they can play again?
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num, guess, tries = 0;
srand(time(0));
num = rand() % 100 + 1;
cout << "Guess My Number Game\n\n";
do {
cout << "Enter a guess between 1 and 100 : ";
cin >> guess;
tries++;
if (guess > num)
cout << "Too high!\n\n";
else if (guess < num)
cout << "Too low!\n\n";
else
cout << "\nCorrect! You got it in " << tries << " guesses!\n";
} while (guess != num);
return 0;
}
I wouldn't recommend you to use rand() and stime since it's a bit old and might give you duplicated numbers, use the modern random library, I do this sometimes to get random number in range:
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(1.0, 10.0);
float rnd = dist(mt);
unsigned int flt = rnd;
you might want to add inside your code a new random number generation each time user gives input and just replace std::uniform_real_distribution<double> dist(1.0, 10.0); with new range you need 2 random if I understood what you want properly

C++ 2 dice rolling 10 million times BEGINNER

I am trying to create a program that will roll 2 dice 10 million times, and output how many times each number is rolled. Along with this, I am tasked with creating a histogram (*=2000) for the outputs.
Here is what I have so far.
/*
Creating a program that counts outcomes of two dice rolls, then show a
histogram of the outcomes.
Section 1 : Simulate ten million times rolls of two dice, while counting
outcomes. (Hint: Use an array of size 13.)
Section 2 : Show the outcome, the numbers of outcomes, and the histogram
(one * designates 20000). Your output must align properly.
*/
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
int i, j, ary[13] = {};
cout << "Please enter the random number seed.";
cin >> j;
srand(j);
for (i = 0; i < 10000000; i++)
ary[die() + die()]++;
for (i = 2; i <= 12; i++)
{
cout << setw(3) << i << " : " << setw(6) << ary[i] << " : ";
for (j = 0; j < ary[i]; j += 2000)
cout << "*";
cout << endl;
}
return 0;
}
EXAMPLE OUTPUT: https://imgur.com/a/tETCj4O
I know I need to do something with rand() % 6 + 1; in the beginning of the program. I feel like I am close to being complete but missing key points! I also realize I have not defnied die() in my ary[]
I recommend creating random seeds from high precision timers such as std::chrono::high_resolution_clock. Then they are not dependent on the user and are actually random. Create the seed always before calling std::rand.
#include <chrono>
auto time = std::chrono::high_resolution_clock::now();
auto seed = std::chrono::duration_cast<std::chrono::milliseconds>(time);
std::srand(seed)
Millisecond precision makes the seed usually unique enough but if the seed is required close to 1000 times a second then i recommend using nanosecond or microsecond precision to be really random.
Best would be to create a function that creates the random seed using high precision timer and the random value and finally makes sure the return value is between 0 and 5 (for 6 sided dice).

How do I find 20 odd numbers starting from a number entered by user? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
So, i was given an assignment to find 20 odd numbers starting from a number entered by user.. I know how to find odd numbers. but I don't know how to find them starting from a number entered by user.
I tried this:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
}
but it outputs the number entered by user 20 times.
As the comment says, you output the num, not newly calculated i, but even if you fix that, you will output only few odd numbers (or none), for example for input 50 there will be no output instead of odd 20 numbers (because 50 <= 20 is always false, so no for body will be executed). Plus you are doing lot of math... while the whole task can collapse to trivial:
#include<iostream>
int main() {
int num;
std::cout << "Enter num: ";
std::cin >> num;
num |= 1; // turn user number into odd one (if it was even)
const int endNum = num + 20*2; // calculate the first odd number after 20 of them (end value)
while (num < endNum) {
std::cout << num << std::endl;
num += 2;
}
}
doing just simple addition +2 in loop.
edit: btw, why num |= 1; guarantees odd number... because integers in computer are stored as binary values, where every digit is different power of two, with the least significant bit corresponding to the zeroth power of two (i.e. value 1). If this bit is set, then the value is odd, because dividing by two does apply from first power of two upward and this bottom bit is remainder. And if it is reset, the value is even, for the same reason, the bottom bit is remainder after you would divide the value by two. The binary or operator |= 1 will set the least significant bit to one, turning any integer value to odd one.
This is the special case, when your task involves calculation based on powers of two. Because all the values in computer are already encoded in the binary way, there are usually shortcuts how to get the result of such calculation. Like for example to get remainder of division by 16 from integer n you can do binary and: n & 15 and you have the remainder. Or to divide by 16 you can shift the unsigned integer value by four bits to the right like n >> 4 to get the result. But this doesn't work with calculations which are not power-of-two based, i.e. remainder after dividing by ten is NOT n & 9, because 9 is 0b1001, so different values will be trimmed down to only values 0, 1, 8 or 9, but remainders after dividing by 10 can be any value from 0 to 9. .. while 15 is in binary 0b1111, so such binary and-mask will produce all values from 0 to 15, and they correspond to the remainder by div 16.
The bug in your code is that you print num instead of i. So just do:
cout<< i <<endl;
^
But you can simplify your code a lot by doing:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
if (num%2 == 0) ++num; // Make sure num is odd
for(i=0; i < 20; ++i){ // Print 20 numbers
cout << (num + 2*i) << endl; // Multiply i by 2 and add it to num
// so that the result is the next odd number
}
}
note
As suggested by Ped7g the line
if (num%2 == 0) ++num; // Make sure num is odd
can be made more simple. Just replace it with
num |= 1; // Set the least significant bit so that num is odd
This loop
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
does not make sense because it checks the variable i instead of the variable num whether it is an odd number. And it is obvious there will be outputted a half of 20 values of i.
The program can look the following way
#include <iostream>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1; // make the first odd number
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n += 2;
}
}
Its output might look the following way
Enter a number: 10
11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
A more correct professional code can look the following way
#include <iostream>
#include <limits>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1;
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n = std::numeric_limits<int>::max() - 2 < n ? std::numeric_limits<int>::min() | 1 : n + 2;
}
}
In this case if the user will enter the maximum integer value then the output will look like
Enter a number: 2147483647
2147483647 -2147483647 -2147483645 -2147483643 -2147483641 -2147483639 -2147483637 -2147483635 -2147483633 -2147483631 -2147483629 -2147483627 -2147483625 -2147483623 -2147483621 -2147483619 -2147483617 -2147483615 -2147483613 -2147483611

C++ generating random numbers inside loop

I want to generate random numbers inside loop but results are always same numbers.
What I'm doing wrong? Thanks.
Code
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
const char duom[] = "U1.txt";
const char rez[] = "U1_rez.txt";
void num_gen(int & x, int & y);
int main(){
srand(time(NULL));
int x, y;
ifstream fd(duom);
fd >> x >> y;
fd.close();
ofstream fr(rez);
for(int j = 1; j <= 4; j++){
num_gen(x, y);
fr << x << " + " << y << " = "<< x + y << endl;
fr << x << " - " << y << " = "<< x - y << endl;
fr << x << " * " << y << " = "<< x * y << endl;
fr << x << " / " << y << " = "<< x / y << endl;
fr << "************" << endl;
}
fr.close();
return 0;
}
void num_gen(int & x, int & y){
x = 3 + (rand() % 10);
y = 3 + (rand() % 10);
}
Result
4 + 8= 12
4 - 8= -4
4 * 8= 32
4 / 8= 0
************
4 + 9= 13
4 - 9= -5
4 * 9= 36
4 / 9= 0
************
9 + 11= 20
9 - 11= -2
9 * 11= 99
9 / 11= 0
************
12 + 8= 20
12 - 8= 4
12 * 8= 96
12 / 8= 1
************
With the advent of C++11/14 you should actually give up using srand & rand & use the more efficient RANDOM NUMBER GENERATING MACHINES declared in the header #include<random>. Illustrating in a simple example :-
#include <iostream>
#include <random> // for default_random_engine & uniform_int_distribution<int>
#include <chrono> // to provide seed to the default_random_engine
using namespace std;
default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count()); // provide seed
int random (int lim)
{
uniform_int_distribution<int> uid {0,lim}; // help dre to generate nos from 0 to lim (lim included);
return uid(dre); // pass dre as an argument to uid to generate the random no
}
int main()
{
for (int i=0;i<10;++i)
cout<<random(10)<<" ";
return 0;
}
One of the outputs of the above code is :-
8 5 0 4 2 7 9 6 10 8
See, the numbers vary from 0 to 10. Give your limits in uniform_int_distribution according to your desired output. This thing seldom fails & you can generate random numbers in greater ranges without worrying about outrageous outputs like you had.
Might be because the the random method is running with time of the computer. So if in the same 1/10000 of a second you computer do all process he need to do, you might read the same number since the random method haven't refresh the value. Try to put a sleep at the end of the for (like sleep(100)) and check if the values changed.
I think your code should generate different "pseudo" random numbers between 3 and 12 at each run, subject to that more of one second has elapsed between each run. Check if all this is really what you want.
Maybe you just run it much faster than the increase in a second when you call to time(NULL), which return the number of seconds since the epoch.
Anyway, your random numbers are not very good because you use the lower order bits. I transcript this excerpt from the rand() man page:
In Numerical Recipes in C: The Art of Scientific Computing (William H.
Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
York: Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
ing comments are made:
"If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."

Outputting Max min and average from a randomized array?

I was wondering if anyone can help me with something I was struggling all day with.
In the code below I dictated an array of randomized numbers from which I have to have pull out the max the min and the average. It all looks fine and good (such a compact software!) But I attain a weird output. I believe I have a finger on what the problem is (say I'm finding the max for the first number but the next number is smaller the software will think that's the biggest number even though integer 14 may be bigger) but I have no idea how to go about fixing this. The minimum value I have no idea why it's wrong it keeps saying it's zero and the average value stays anywhere from 10-19 which is impossible considering the range of randomized numbers goes from 1 to 1000. I was never taught how to organize random numbers in an array, so I just have no idea how to go about fixing this. Any help will be super awesome! I really struggled with this program and even scrapped it multiple times, if it's only a simple mistake I overlooked I would feel awfully embarrassed I'll post the code and an example output below.
Thanks for taking your time, I hope you have a wonderful day!
#include <cmath>
#include <iostream>
#include<cstdlib>
#include <ctime>
#include <time.h>
#include <iomanip>
using namespace std;
int main()
{
//Defining variables
//DEFINE SIZE
const int ARRAY_SIZE =20;
//Index variable
int i;
//For finding average
double sum=0;
double max_value;
double min_value;
//Keep all numbers sane
cout.precision(5);
srand((unsigned)time(0));
double main_array[ARRAY_SIZE];
//Header
cout << "Element number \t\t" << "Random Number\n\n" << endl;
//Assigning random values into array.
for (i=0; i< ARRAY_SIZE; i++)
{
max_value=0;
min_value=0;
//Randomizer
double ran = 0 + (rand()/((float)RAND_MAX/(1000-0)));
main_array[i] = ran;
cout << "\t" << i << "\t\t" << main_array[i] << endl;
//Find average
sum= (sum + main_array[i]);
sum= sum/(ARRAY_SIZE+1);
//Initalizing
for (int i = 0; i < ARRAY_SIZE; i++)
{
if ( min_value > ran)
min_value = main_array[i];
if (max_value < ran)
max_value = main_array[i];
}
}
cout <<"Average Value is: " << sum << endl;
cout <<"\nThe Minimum Value Is: " << min_value << endl;
cout <<"\nThe Maximum value Is: " << max_value << endl;
system ("pause");
return 0;
}
An output example would be
Element number Random Number
0 791.62
1 542.04
2 879.57
3 875.39
4 38.057
5 73.702
6 973.27
7 22.431
8 830.26
9 444.59
10 276.89
11 888.12
12 827.17
13 900.45
14 883.72
15 201.15
16 317.64
17 649.83
18 443.98
19 683
Average Value is: 33.603
The Minimum Value Is: 0
The Maximum value Is: 791.62
Press any key to continue . . .
Unless you must do otherwise, use std::min_element to find the minimum, std::max_element to find the maximum, and std::accumulate to find the sum.
If you absolutely must do this on your own, you usually want to initialize your minimum and maximum to the first element in the collection, then look for others that are smaller/larger:
int mininum = array[0];
int maximum = array[0];
for (int i=1; i<array_size; i++) {
if (array[i] < minimum)
minimum = array[i];
if (array[i] > maximum)
maximum = array[i];
}
Before you start looping, create a min, max, and total. Then when you are creating each element of the array, also check whether it is less than the min or more than the max. Also add that number to your total. At the end, outside the loop, divide the total by the number of elements to get your average.
You definitely shouldn't be iterating through the whole array each time you add an element, and you shouldn't be resetting your min and max each time through the loop. You also shouldn't set your min to 0 if all your numbers are going to be more than 0, because it will never be updated.