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.
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
}
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.
#include<iostream>
#include<cmath>
#include<string>
#include<ctime>
#include<vector>
#include<algorithm>
#include<iomanip>
usingnamespace 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;
}