1、算法背景:
大家知道,微信拼手氣紅包和普通紅包兩種。普通紅包每個人搶到的金額是固定的(總額的平均數),拼手氣紅包是隨機金額(每個人搶到的是隨機的,差別可能非常大,有的人搶到的是1分,有的搶到的可能是幾元、十幾元、幾十元),目前的搶紅包算法只能輸入兩個參數,即總金額、總人數。
2、算法要求:
現要求同學們設計一個改進的搶紅包算法,可以設定總金額(total)、總人數(num)、搶到的最低金額(min)和最高金額(max),這樣就可以控制每個搶紅包的,搶到的不會太少,也不會太多。
(1) 先用自然語言給出算法設計的思想:
第一步:輸入紅包金額總金額,紅包個數,紅包金額最低/最高額度。
第二步:判斷帶輸入數據是否滿足算法要求,不滿足輸出提示信息,並重新輸入數據。
第三步:生成一個隨時紅包金額
第四部:判斷紅包金額是否滿足條件,如果滿足,繼續生成下一個紅包金額,如果不滿足在
此生成新的隨機紅包金額,知道滿足條件。
第五步:輸出搶紅包的過程信息
(2) 進行異常檢查與處理;
(3) 給出C語言源代碼實現,運行結果展示;
源代碼如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input();
int range_random_price(int start_price, int end_price);
void redPackets(double Total, int num, double Min_price, double Max_price);
int maxx = 0, maxx_index = -1;
int main()
{
input();
return 0;
}
// 數據輸入
void input()
{
double total;
int num;
double min_price, max_price;
printf("請輸入以下數據:\n");
printf("紅包總金額: ");
scanf("%lf", &total);
putchar('\n');
printf("紅包數量: ");
scanf("%d", &num);
putchar('\n');
printf("紅包最低金額: ");
scanf("%lf", &min_price);
putchar('\n');
printf("紅包最高金額: ");
scanf("%lf", &max_price);
putchar('\n');
redPackets(total, num, min_price, max_price);
}
// 生成(a, b) 之間的隨機數
int range_random_price(int start_price, int end_price)
{
return rand()%(end_price-start_price+1) +start_price;
}
// total :總金額(元) num:人的個數 min_price max_price :最低/最高金額
void redPackets(double Total, int num, double Min_price, double Max_price)
{
// 剛開始金額全部擴大100倍轉變成整數,最後輸出的再除以一百,轉變爲浮點數
int total = (int)Total*100;
int min_price = (int)Min_price*100;
int max_price = (int)Max_price*100;
if((total*1.0 / num) - min_price*1.0 < 1e-9)
{
printf("您輸入的總金額過小,或者搶的紅包金額最低限度過大,請重新輸入\n");
input();
return ;
}
printf("搶紅包結果如下:\n");
for(int i = 1; i < num; i++)
{
int random_price;
while(1)
{
random_price = range_random_price(min_price, max_price);
//判斷剩下的金額是否滿足條件
if((total - random_price)*1.0 / (num - i) - min_price*1.0 >= 1e-9)
break;
}
if(maxx < random_price)
maxx = random_price, maxx_index = i;
total -= random_price;// 剩餘金額
printf("第 %d 個人搶到的紅包金額爲 %.2f, 紅包剩餘金額爲 %.2f\n", i, (double)(random_price/100.0), (double)(total/100.0));
}
if(maxx < total)
maxx = total, maxx_index = num;
// 輸出最後一個人的紅包金額
printf("第 %d 個人搶到的紅包金額爲 %.2f, 紅包剩餘金額爲 0.00\n", num, (double)(total/100.0));
printf("運氣王是 %d 號\n", maxx_index);
}
程序運行結果: