Function stuck

I've written some code to randomly generate probabilities:


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
int Queue::car_per_hr()
{

	srand( time( NULL ));
	int prob = rand() % + 101; // Probability in percentage from 0 to 100
	int cars; //no of cars per hr

	if( prob >= 0 && prob <= 20 ){
		cars = rand() % 13; // 20% probability of car arriving per minute
								// 20% of 60 =  12
								// So 0-12 cars per hr
		cout << "1st prob" << cars << endl;
	}
	else if( prob > 20 && prob <= 40 ){ // Generate no cars in hr for prob of 21%-40%
		cars =  rand() % 11 + 13;  // 13-24 cars per hr
		cout << "2nd prob: " << prob << "\n No.cars: " << cars << endl;
	}
	else if( prob > 40 && prob <= 60 ){ // Gen for 41%-60%
		cars = rand() % 11 + 25;   // 25-36 cars
		cout << "3rd prob" << prob << "\n No.cars: " << cars << endl;
	}
	else if( prob > 60 && prob <= 80 ){ // Gen for 61%-80%
		cars = rand() % 11 + 37;   // 37-48 cars
		cout << "3rd prob" << prob << "\n No.cars: "  << cars << endl;
	}
	else{ // From 81%-100% prob
		cars = rand() % 11 + 49;	// 49-60 cars
		cout << "4th prob"  << prob << "\n No.cars: " << cars << endl;
	}
	
	return cars;
}


So it checks through the range of possibilities: 0-20%, 21-40% etc.

I then have this to implement it:

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
#include <iostream>
#include <ctime>
#include "queue.h"

using namespace std;

int main(){

	Queue car_wash;
	int NO_HOURS;

	cout << "How many hours would you like this car wash simulator to simulate?" << endl;
	cin >> NO_HOURS;

	for( int j = 0; j < NO_HOURS; j++ ){
		car_wash.POT( car_wash.car_per_hr() );
	}

	car_wash.FREQ();

	system( "PAUSE" );
	getchar();
	return 0;

}


For some reason though, everytime I call the car_per_hr() function, the probability just stays the same. It's output is always locked to the same thing it had to begin with.

What am I doing wrong?

Additional code can be provided if this is not sufficient.
I assume you mean all the numbers for a specific run are the same. The number will vary between individual runs, right?

You are reseeding the random number generator every time you call car_per_hr(). The multiple calls will all very likely be within the same clock second, so srand will reseed with the same value each time.

Instead of calling srand in the car_per_hr() function, call it in main(), say in line 11.
Use srand( time( NULL )); only once - in your main function

1
2
3
4
5
int main()
{
       srand(time(NULL));
       ...
}


that should solve the problem
Last edited on
Ye used srand in my int main instead of calling it everytime car_per_hr() function is called.

Thanks
Registered users can post here. Sign in or register to post.