-
1 Attachment(s)
Functions for Die
So i have been trying to make a program that uses a function to roll a dice. I made the program so that the dice roll is within main but I'd like to make the dice roll a function all in itself so that i can use it for multiple things. This is what i have so far in the file attached and below copied and pasted:
#include <iostream>
#include <ctime> // for time function
#include <cstdlib> // for rand and srand functions
using namespace std;
int target, roll;
long count;
int rollDie(int target, int roll) {
long x;
while(roll != target){
roll = rand() % 6 + 1;
x++;
}
return x;
}
int main(){
srand((int)time(0));
cout << "Enter target (ctrl-z to exit): ";
cin >> target;
while (cin) {
//display stats
cout << endl << "target: " << target << endl;
cout << "number of rolls: " << rollDie() << endl;
//prompt and read next target
cout << "enter target (ctrl-z to exit): ";
cin >> target;
}
//exit
cout << endl << "Exiting.." << endl;
return 0;
}
-
Re: Functions for Die
So... what are you having troubles with?
I already see you are trying to use your rollDie() function incorrectly.
It is supposed to accept two arguments, but when you call it, you don't pass anything.
Second, do not call local variables the same name as global variables.
-
Re: Functions for Die
Please use code tags and indent your code.
-
Re: Functions for Die
One roll of a die,
Code:
int rollDie() {
return rand() % 6 + 1;
}
-
Re: Functions for Die
Alright well I figured it out and like everything it was easier than I was making it. And thanks for the info on code tags I'll use those next time. It was just a matter of taking the loop out of the function and just having the loop in main and each pass through the loop calling the function.