厦门大学上机题——发红包
题目描述:
微信发红包的问题,输入两个数m和n,分别表示要发的钱数以及红包总数,然后输出每个人发到了多少钱。
算法思路:
主要用到的是rand()%m这个函数,我们还要考虑是不是得保留两位小数,以及保证红包金额不为0等细节。
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main() {
double total_money;
int n;
cout << "输入红包总数金额:";
cin >> total_money;
cout << "输入红包数:";
cin >> n;
double* m = new double[n];
srand((int)time(0));
for (int i = 0;i < n - 1;i++) {//分配1到n-1的金额
double temp;
do {//保证分配红包金额不会出现0
temp = rand() % (int)(total_money * 100) * 0.01;
} while (temp >= total_money || temp <= 0);
total_money -= temp;
m[i] = temp;
}
m[n - 1] = total_money;
cout << "每个人抢到的金额为:" << endl;
for (int i = 0;i < n;i++) {
cout << m[i] << '\t';
}
return 0;
}
运行测试结果: