微信发红包的随机算法
随机数:使用 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;
}