Srand and rand

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?


#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;


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;
}
You are generating your random numbers before you set the seed so you're getting the exact same default initial sequence every time.
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.

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
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;

int main() {
    const int 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]
Last edited on
dutch,
I now see the issue! Thank you for posting a go-by code as well as explaining why that needed to happen, very helpful!

I'll make sure to do that for future posts, thanks again!
Topic archived. No new replies allowed.