c++ random number generator that allows user to choose range -


i have come random number generator generate 5 random numbers within range of 2 number entered user. example: user first enters 1 10. random numbers generated 2,3,4,5,8. can give me 1 random number 5 times, not 5 different random numbers. please see below. appreciated. thanks!

#include <iostream> #include <cstdlib> #include <ctime> using namespace std;  int main () {         int num1, num2, randnum, seed;           cout << "enter number 1.\n";         cin >> num1;         cout << "enter number 2.\n";         cin >> num2;  seed = num1 - num2; randnum = rand() % seed + 1;          cout << randnum << "\n";         cout << randnum << "\n";         cout << randnum << "\n";         cout << randnum << "\n";         cout << randnum << "\n";  return 0; } 

randnum isn't modified each time call cout displays same value. if want work need use loop this

for(int i=0;i<5;i++){     randnum = rand() % seed + num2;     cout << randnum << "\n"; } 

the second mistake using +1 instead of +num2 generate number within range expect, assuming num2 smaller num1.

there 1 more thing should consider name of variable seed. seed use initialize random number generator. here variable here express range. different results when run program every time, need initialize rand something, example this: srand(time(0));


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -