发红包程序

//设计一个发红包程序,500分5个人分。

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int doss(int start, int end) { return rand() % (end - start + 1) + start; }

/**发红包算法

把数量是tot(单位是分)的钱随机分k个红包,

保证每一个红包不少于1分钱,且总数为tot

*/

void luckyMoney(int a[], int k, int tot) {

  if (tot <= 0 || tot < k) {  //分配失败

    puts("Invalid number!");

    return;

  }

  //红包分配算法,最后一次不用随机避免产生结余

  int i;

  for (i = 0; i < k - 1; i++) {

    a[i] = doss(1, tot - (k - i + 1));

    tot -= a[i];

  }

  a[k - 1] = tot;  //剩余金额直接放入最后一个

  //寻找运气王(第一次找到最大值的序号)

  int maxIndex = 0;

  for (i = 1; i < k; i++)

    if (a[i] > a[maxIndex]) maxIndex = i;

  //格式化输出

  for (i = 0; i < k; i++) {

    printf("%.2f ", a[i] / 100.0);

    if (i == maxIndex) printf("*Luckiest guy!");

    printf("\n");

  }

  printf("\n");

}

 

int main() {

  srand(time(NULL));

  int a[100];

  int tot = 500;

  int n = 5;

  luckyMoney(a, n, tot);

  return 0;

}

posted @ 2017-08-16 21:30  我大概是只废喵  阅读(566)  评论(0编辑  收藏  举报