[Edited]Why Doesn't this Work?

Hi,

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
long double probability(unsigned int numbers, int unsigned picks) // takes a field of numbers and the amount of numbers one can select as arguments.
{
long double result = 1.0;
long double 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

long double probability(unsigned numbers, unsigned picks, unsigned powerball);
int main()
{
using namespace 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;
}

long double probability(unsigned numbers, unsigned picks, unsigned powerball)
{
long double result = 1.0; 
long double 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, long double (*pb)(unsigned, unsigned))
{
    double chance;
 
    chance = pb(field,fieldselect)*pb(meganum,megaselect);
 
    return chance;
}


Thanks in advance!

Leon
Last edited on
For your original code: integer division returns an integer, so 1/powerball is 0

but it seems like too much work if the number is not entered by the user
¿eh? ¿why does it matter where do you get the number from?
The output always displays a chance of 0 regardless of input.
Yes: On line 30 you have an interger division which results to 0 if powerball is greater 1. Change it to result *= (1.0 / powerball);
Thank you coder777 for clarifying it! Much appreciated :)
Topic archived. No new replies allowed.