随机红包(C++)

微信发红包的随机算法
随机数:使用 rand() 和 srand() 产生指定范围内的随机整数的方法:“模除+加法”的方法。
如要产生 [m,n] 范围内的随机数 num,可用:
int num=rand()%(n-m+1)+m;(即 rand()%[区间内数的个数]+[区间起点值])

参考:https://blog.csdn.net/weixin_42785489/article/details/88295271

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <math.h>
#include <vector>
using namespace std;
int main()
{
	//num代表总人数,best代表手气最佳的索引,total表示总金额 
	int num,best;cin>>num;
	double total;cin>>total;
	//生成随机数
	srand((unsigned)time(NULL));
	//a表示每个人的随机数,b表示每个人获得的红包金额 
	vector<double> a(num),b(num); 
	//随机红包总和    实际红包总和 
	double suma = 0.0,sumb = 0.0;
	
	int max = 0;//找出红包值得最大值,从0开始 
	//生成num个随机数
	for (int i = 0; i < num; i++)
	{
		a[i] = rand() % 100;// 生成实际的随机数
		if (a[i] > max) {
			max = a[i];best = i;//获取手气最佳
		}
		suma += a[i];
	}
    //生成前n-1个的实际金额
	for (int i = 0; i < num- 1; i++)
	{
		b[i] = a[i] / suma * total;//按照随机数计算每个人实际获得的金额
		float b_temp= round(b[i] * 100) / 100.0;//将红包金额保留两位小数
		sumb += b_temp;	
		cout << "第" << i + 1 <<"个人的红包是:" <<b_temp<<" ";
		if (best == i) {cout << "(手气最佳)" << endl;}
		else {cout << endl;}
	}
	//最后一人的红包金额等于总金额减去前面的金额。
	cout << "第" << num << "个人的红包是:" << round((total - sumb) * 100) / 100.0;
	if (best == num - 1) {cout << "(手气最佳)" << endl;}
	else {cout << endl;}

	return 0;
 } 

在这里插入图片描述

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值