#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int golf();
int hotel();
int main(){
hotel();
}
int golf(){
srand(time(NULL));
rand() % 6 + 1;
}
int hotel(){
int r1;
int r2;
int counter = 1;
while(counter > 0){
if(r1 != r2){
cout << counter << endl;
counter++;
}
golf();
}
return hotel();
}
I'd like to create a function that randomly rolls two dice and outputs how many times it takes for both dice to equal the same number. This is my attempt
srand is for C random numbers and is not recommended, c++ uses random, but you can read that tutorial later. Just be aware not to use it after you get past beginner problems.
c++ uses <cmath> not <math.h>. The difference is minor but it matters later on.
#include <iostream>
#include <math.h>
#include <string>
usingnamespace std;
int golf();
int hotel();
int main()
{
srand(time(NULL)); //moved
//hotel(); disabled not sure what its supposed to do.
int value = 0;
value = golf(); //like this store the value created in golf into a variable to use later.
cout << value << endl; //show the random number
//or this
cout <<golf() << endl; //the random number is printed but lost, you can't get it back, but you can see it.
}
int golf()
{
return (rand() % 6 + 1); //returns the value now.
}
int hotel()
{
int r1;
int r2;
int counter = 1;
while(counter > 0)
{
if(r1 != r2)
{
cout << counter++ << endl;
//counter++; //combined above
}
//golf(); //this does nothing. should be like what I did in main, x=golf(); format
}
//return hotel(); //this is wrong but may compile. what result do you want to return?
//the function wants an integer result, but what integer, and what does it mean?
}
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int numberUntilSame()
{
return 1 + ( ( rand() - rand() ) % 6 ? numberUntilSame() : 0 );
}
int main()
{
srand( time( 0 ) );
cout << "Number of pairs thrown until the same = " << numberUntilSame() << '\n';
}
Or let's see how good rand() is. (Average here should be 6.0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int numberUntilSame()
{
return 1 + ( ( rand() - rand() ) % 6 ? numberUntilSame() : 0 );
}
int main()
{
srand( time( 0 ) );
constint N = 10000;
int sum = 0;
for ( int i = 0; i < N; i++ ) sum += numberUntilSame();
cout << "Average number until the same = " << (double)sum / N << '\n';
}