廈門大學上機題——發紅包
題目描述:
微信發紅包的問題,輸入兩個數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;
}
運行測試結果: