Simulate rolling a die using functions

Hello,

I have been tasked by my professor to create a program that simulates a dice roll using functions. The problem that I am having is that I don't know how to get my function to give the answer in the main() area. This is what I have so far.

#include<iostream>
#include<cmath>
#include<string>
#include<ctime>
#include<vector>
#include<algorithm>
#include<iomanip>


using namespace std;
int rolldie(int rand_number);

int main(){
srand(time(NULL));

cout << "This program rolls a dice once and prints the number.";

system("pause");
return 0;
}
int rolldie(int rand_number){
rand_number = 1 + rand() % 6;
return rand_number;
}
Well you're almost done. Your function is correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main(){
srand(time(NULL));

cout << "This program rolls a dice once and prints the number.";
int randomNumber = 0; // creating a variable to send into the function
int catchNumber = rolldie(randomNumber) // calls the function and sends in randomNumber  as parameter, and the returning value of that functions is stored in catchNumber;

cout << << endl << "The Random Number is: " << catchNumber << endl; // prints out random number

system("pause");
return 0;
}
int rolldie(int rand_number){
rand_number = 1 + rand() % 6; // Probably better to do rand() % 6 +1;
return rand_number; // this returns the random number
}
Last edited on
@Blev 58

Actually, it's much easier to get the random die number than the way TarikNeaj showed. You don't need to send anything to the function. Just call it, like so.
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<cmath>
#include<string>
#include<ctime>
#include<vector>
#include<algorithm>
#include<iomanip>


using namespace std;
int rolldie();

int main()
{
	srand(time(NULL));
	int roll;
	cout << "This program rolls a dice once and prints the number." << endl;
	roll = rolldie();
	cout << "You rolled a " << roll << endl;
	system("pause");
	return 0;
}
int rolldie()
{
	return 1 + rand() % 6;
}
Topic archived. No new replies allowed.