Question:
a calculating function that uses a for loop to “roll” N random numbers?
anonymous
2013-04-16 21:14:49 UTC
Write a calculating function that uses a for loop to “roll” N random numbers, each between 1 and 6. It then returns to the caller the percentage of rolls on which we rolled an odd number bigger than X.

double percentageOdds(int N, int X) {

int oddsX = 0; // number of odd numbers > X we got so far

// insert your C++ code here

}

// test driver

int main() {

double p;
p = percentageOdds(1000, 3);
cout << “I tossed 1000 dice, and “ << x << “ times I got an odd number bigger than 3.” << endl;

system(“pause”);
}
Three answers:
?
2013-04-16 23:47:36 UTC
This is how you could do it.

James Bond's code is using "1000" in function "double percentageOdds(int N, int X)" ,

where he should have used N.



#include

#include

#include

using std::cout;

using std::cin;

using std::endl;



double percentageOdds(int N, int X)

{

int oddsX = 0; // number of odd numbers > X we got so far

// insert your C++ code here

int rnd = 0;

for (int i = 0; i < N; i++) {

rnd = rand() % 6 + 1;

if (rnd % 2 && rnd > X) ++oddsX;

}

return oddsX * 1.0 / N;

}



// test driver

int main()

{

srand(time(0));

double p;

p = percentageOdds(1000, 3);

cout << "I tossed 1000 dice, and " << p << " times I got an odd number bigger than " << 3 << endl;

return 0;

}
?
2017-01-04 15:31:53 UTC
Ryan Adams - Strawberry Wine Lucinda Williams - end results of My hard artwork Tom Petty - Honey Bee The White Stripes - Sugar by no potential Tasted So sturdy Wilco - candy Floss John Lennon - chilly Turkey Led Zeppelin - Custard Pie
James Bond
2013-04-16 21:33:27 UTC
double percentageOdds(int N, int X) {



int oddsX = 0; // number of odd numbers > X we got so far



// insert your C++ code here



for(int i=0;i<10000;i++)

{

int r=rand()%6+1; // random(6); also we can use

if(r%2&&r>X)oddsX++;

}

return oddsX/10000.0;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...