I'm currently studying from C++ Premier Plus, and one recent exercise I had to tackle involved modifying an existing piece of code that calculates probability so that it could accommodate a 'power ball: the original probability times another one.
Here is the original code:
1 2 3 4 5 6 7 8 9
longdouble probability(unsignedint numbers, intunsigned picks) // takes a field of numbers and the amount of numbers one can select as arguments.
{
longdouble result = 1.0;
longdouble n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--) //calculates probability of getting all the selected numbers right
result = result * n / p ;
return result;
}
What I don't understand is why the following code doesn't work properly assuming there is only one number you need to get right for the powerball.
#include <iostream>
longdouble probability(unsigned numbers, unsigned picks, unsigned powerball);
int main()
{
usingnamespace std;
double total, choices, powerball;
cout << "Enter the total number of choices on the game card and\n""the number of picks allowed, plus the power ball field:\n";
while ((cin >> total >> choices >> powerball) && choices <= total)
{
cout << "You have one chance in ";
cout << probability(total, choices, powerball);
cout << " of winning.\n";
cout << "Next two numbers (q to quit): ";
}
cout << "bye\n";
return 0;
}
longdouble probability(unsigned numbers, unsigned picks, unsigned powerball)
{
longdouble result = 1.0;
longdouble n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
result *= (1 / powerball); // area in question
return result;
}
The output always displays a chance of 0 regardless of input. I'm using Microsoft Visual C++ 2010.
Here is the correct answer in the form of another function. I do understand why this would work in case of more than one powerball selection, but it seems like too much work if the number is not entered by the user. Is there an alternate route?
1 2 3 4 5 6 7 8
double lotterychance(int field, int fieldselect, int meganum, int megaselect, longdouble (*pb)(unsigned, unsigned))
{
double chance;
chance = pb(field,fieldselect)*pb(meganum,megaselect);
return chance;
}