天天看點

C++ Primer Plus 7.4

//test 7.4 lotto--probability of winning

#include <iostream>

long double probability(unsigned numbers, unsigned picks);

int main()

{

using namespace std;

/*

//one field

double total,choices;

cout<< "Enter the total number of choices on the game card and/n"

"the number of picks allowed:/n";

while((cin>> total>> choices)&& choices<=total)

{

cout << "You have one chance in ";

cout << probability(total,choices); //compute the odds

cout << " of winning./n";

cout << "Next two numbers (q to quit): ";

}

*/

//two field

//

double total_a,choices_a,total_b,choices_b;

cout<< "Enter the total number of choices on the game card and/n"

"the number of picks allowed in first field:/n";

while((cin>> total_a>> choices_a)&& choices_a<=total_a)

{

cout<< "The other two numbers in second field: ";

if((cin>> total_b>> choices_b)&& choices_b<=total_b)

{

cout << "You have one chance in ";

cout << probability(total_a,choices_a)*probability(total_b,choices_b); //compute the odds

cout << " of winning./n";

}

else

break;

cout << "Next two numbers (q to quit): ";

}

//

cout << "bye/n";

return 0;

}

long double probability(unsigned numbers, unsigned picks)

{

long double result = 1.0;

long double n;

unsigned p;

for(n=numbers, p=picks;p>0; n--,p--)

result = result * n / p;

return result;

}

繼續閱讀