how to call random function in main

how can i call a random function in main function
please help

You need to be more specific here :)

If I have understood you right, you want your program to randomly pick from a set of functions and run that function? - Just generate a random number, lets say between 1 - 5... and use a switch statement to check the number generated.


okay m sorry i need somthing like this

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

char random(int computer, char cpu_choice)
{
	computer = rand() % 3;
		
		if (computer == 0)
		{
			cpu_choice = 'R';
		}
		
		else if (computer == 1)
		{
			cpu_choice = 'P';
		}
			
		else
		{
			cpu_choice = 'S';
		}
	return cpu_choice;
}

int main()
{
      srand(time(0));
      char cpu_choice =random(); // this is what i am not sure of
    cout << cpu_choice<<endl;
}
Last edited on

Well, your error would be caused because the function random expects two parameters (integer and char) passed to it when its called.

Altered your code a little...

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

#include <iostream>
#include <ctime>

char random()
{
	int computer = rand() % 3;

	switch (computer)
	{
	case	0:
		return('R');
	case	1:
		return('P');
	default:
		return('S');
	}
}

int main()
{
	srand(time(0));
	char cpu_choice = random(); 
	std::cout << cpu_choice << std::endl;
}


Have you seen this tutorial?

Functions
http://www.cplusplus.com/doc/tutorial/functions/

Andy
Topic archived. No new replies allowed.