C++ primer plus 第七章编程练习:4. 许多州的彩票发行结构都使用如程序清单7.4所示的简单彩票玩法的变体。

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);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值