利用随机数抢红包

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "time.h"
#include "iomanip"
#include "math.h"

using namespace std;

int main()
{
	int i, number;	
	int bestMoney;	//手气最佳的人
	float total;  //总金额
	
	cout << "输入金额:";
	cin >> total;
	cout << "输入红包份数:";
	cin >> number;

	srand((unsigned)time(NULL));
	float a[100];	//设置可以抢红包的最大人数
	float b[100];	//记录红包金额
	float suma = 0;		//随机数总和
	float sumb = 0;		//红包总和
	int max = 0;

	for (i = 0; i < number; ++i)
	{
		a[i] = rand() % 100+1;  //防止出现0
		if (a[i] > max)
		{
			max = a[i];
			bestMoney = i;
		}

		suma += a[i];
	}

	for (i = 0; i < number - 1; ++i)
	{
		b[i] = a[i] / suma*total;  //按照随机数确定每个人获得的红包金额
		sumb += round(b[i] * 100) / 100;  //红包金额保留两位小数

		cout << "第" << setiosflags(ios::right) <<setw(3)<< i + 1 << "个人的红包是:" << setiosflags(ios::right)
			<< setw(6) << setiosflags(ios::fixed) << setprecision(2) << round(b[i] * 100) / 100;
		if (i == bestMoney)
		{
			cout << "(手气最佳)" << endl;
		}
		else
		{
			cout << endl;
		}
	}

	//最后一人的红包等于总金额减去前面的金额
	cout << "第" << setiosflags(ios::right) <<setw(3)<< number << "个人的红包是:" << setiosflags(ios::right)
		<< setw(6) << setiosflags(ios::fixed) << setprecision(2) << round((total - sumb) * 100) / 100;

	if (number - 1 == bestMoney)
	{
		cout << "(手气最佳)" << endl;
	}
	else
	{
		cout << endl;
	}
	system("pause");	
	return 0;
}	
发布了36 篇原创文章 · 获赞 6 · 访问量 2053

猜你喜欢

转载自blog.csdn.net/the_sea1/article/details/103458129