Develop a program that uses a randomly generated number to select 1 of 3 functions to show the user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"


#include <iostream>
int main(){
	int a;
	a = (rand() % 3) + 1;
	std::cout << a;
	switch (a){
	case 1:int x;
		x = 1; {
			std::cout << "First";
		}break;
	case 2:int u;
		u = 2; {
			std::cout << "Second";
		}break;
	case 3:int z;
		z = 3; {
			std::cout << "Third";
		}
	}
}

Always shows Third case.Not random.Help!
Last edited on
You need to seed.

Add this - #include <time.h>
And put this at the top of your program - srand (time(NULL));

Thank you! But why is this step necessary, excuse my ignorance?
Read here - http://www.cplusplus.com/reference/cstdlib/srand/

If you want to do propar random generating, then you don't want to use rand() since it's pretty shittie - https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

You instead want to use the header <random> - http://www.cplusplus.com/reference/random/

(There are examples all over the internet and in the video above)
Okay!Thanks!
Very good question! =) Although I do not have a perfect explanation to the why, other than telling you that rand()% will not actually give you a real random number. If you want a good explanation I suggest you google for your answer. as to the solution include the library <ctime> and add srand(time(NULL)); to reset the counter. It should give you different results every time you run your program. Hope you google for your explanation though. Good Luck.
Thanks TarikNeaj for the wonderful knowledge!
Topic archived. No new replies allowed.