4. 许多州的彩票发行结构都使用如程序清单7.4所示的简单彩票玩法的变体。在这些玩法中,玩家从一组被称为域号码(field number)的号码中选择几个。例如,可以从域号码1~47中选择5个号码;还可以从第二个区间(如1~27)选择一个号码(称为特选号码)。要赢得头奖,必须正确猜中所有的号码。中头奖的几率是选中所有域号码的几率与选中号码几率的乘积。例如,在这个例子中,中头奖的几率是从47个号码中正确选取5个号码的几率与从27个号码中正确选择1个号码的几率的乘积。请修改程序清单7.4,以计算中得这种彩票头奖的几率。
// lotto.cpp -- probability of winning
#include <iostream>
// Note: some implementations require double instead of long double
long double probability1(unsigned numbers, unsigned picks);
long double probability2(unsigned numbers);
int main()
{
using namespace std;
double total, choices;
// cout << fixed;//使用一般方式输出数字!
cout << "Enter the total filed number of choices on the game card and\n"
"the filed number of picks allowed:\n";
while ((cin >> total >> choices) && choices <= total){
cout << "the probability of wining about field number:\n";
cout << 1.0/probability1(total, choices) << endl;// compute the odds
cout << "please enter the total numbers of the special part:";
int total_special;
cin >> total_special;
cout << "the probability of wining about special number:\n";
cout << probability2(total_special) << endl;
cout << "the total probability is: ";
cout << (1.0/probability1(total, choices)) * probability2(total_special);
break;
}
cout << "bye\n";
// cin.get();
// cin.get();
return 0;
}
// the following function calculates the probability of picking picks
// numbers correctly from numbers choices
long double probability1(unsigned numbers, unsigned picks)
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p;
return result;
}
long double probability2(unsigned numbers) {
return long double (1.0 / numbers);
}