admin管理员组

文章数量:1646316

最近对红包金额分配感兴趣,便整理了一个较简单的分配算法

思路:主要是通过随机函数对金额随机分配,由于金额与份数不断变化,如何保证分配前等概率呢?

本例是将金额等分,取得均值,但第一份取左和取右等概率,故其最大值为右份边界。

代码:

 

#include<iostream>

#include<iomanip>

#include <stdlib.h>
#include <time.h>
using namespace std;
void RandHongBao(float total_money,int n)
{
    int i=1;
    float max_money=0,money;
    srand(time(0));//设置时间随机种子
    while(n>1)
       {
              max_money=total_money/n*2;//最大值
              money=(rand()%(int)(max_money*100)+(int)0.01*100)/100.0+0.01;//乘以100除以100是为了保留两位小数
              total_money-=money;
              cout<<fixed<<setprecision(2)<<"第"<<i++<<"个红包有"<<money<<"元"<<endl;
              n--;
       }
       money=total_money;//最后一个红包
       cout<<fixed<<setprecision(2)<<"第"<<i<<"个红包有"<<money<<"元"<<endl;
}
int main()
{
       float Total_money;//红包的总金额
       int N;
       cout<<"请输入红包金额 份数:";
       cin>>Total_money>>N;
       RandHongBao(Total_money,N);
       return 0;
}

截图:

此处提供可运行插件下载:https://pan.baidu/s/1EGNFTFf8Pl6ZfX7Xwvrd5g

 

本文标签: 红包算法金额分配qq