I am working on an assignment where you have to generate 2 random numbers and then find the sum of those 2 numbers. Every time I enter a seed to initiate, the only numbers that come up are 42 and 468.Can someone help lend some advice?
int main()
{
const int MAXRANGE = 500; //Sets max range up to 500
int number1 = 1 + rand() % MAXRANGE;
int number2 = 1 + rand() % MAXRANGE;
int total = (number1 + number2);
unsigned seed;
cout << "Key in a number and hit the enter key to display an additional problem\n";
cout << endl;
cin >> seed;
srand(seed);
cout << endl; //blank space
cout << "Press the enter key when you are ready to see the answer.\n";
cin.ignore();
cout << endl; //blank space
cout << right << setw(7) << number1 << endl;
cout << "+" << right << setw(6) << number2 << endl;
cout << " -----\n";
cout << right << setw(7)<< total << endl;
return 0;
}
Repeater,
Thank you for the fast response! I attempted to do what you said, but unfortunately it still comes out the same numbers. I moved the unsigned seed before the random number generation, but that did not work, so I dont think i am on the same page as you. In what part of my code do you think the issue is?
Each statement is executed in order. So number1 and number2 are given values from rand() and then only later do you call srand, seeding the RNG. Simply moving seed before the initialization of number1 and number2 won't fix it. You need to move the srand(seed) call before the rand() calls.
#include <iostream>
#include <iomanip>
#include <cstdlib>
usingnamespace std;
int main() {
constint MAXRANGE = 500;
unsigned seed;
cout << "Key in a number and hit the enter key to display an additional problem\n";
cin >> seed;
cin.ignore(); // eat the newline character
srand(seed);
int number1 = 1 + rand() % MAXRANGE;
int number2 = 1 + rand() % MAXRANGE;
int total = number1 + number2;
cout << setw(7) << number1
<< "\n+"
<< setw(6) << number2 << endl;
cout << "\nPress the enter key when you are ready to see the answer.\n";
cin.ignore();
cout << setw(7) << number1
<< "\n+"
<< setw(6) << number2
<< "\n ------\n"
<< setw(7)<< total << endl;
return 0;
}
BTW, you should use code tags when you post code, like this:
[code]
paste your code in between the tags
[/code]