关于如何产生随机红包金额问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestRandom
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        /// <summary>
        /// author:bruce 2016-05-23
        /// title:关于如何在不定金额和不定人数中随机红宝数问题
        /// 基本要点:
        /// (1)这里需要特别注意,随机红包轮数要比实际小一轮。最后一轮是总金额减去前面的总和
        /// (2)每次随机的范围是1-总金额-人数+轮数-sum(前面的随机结果),自行思考一下为什么需要这么写?
        /// (3)每次得到结果需要存放在数组中去
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //定义参数
            double total = 100;//红包总金额
            int count = 10;//人数

            //定义存储已经随机出来的结果,数组的长度和人数一致
            double[] result = new double[count];
            //循环处理产生随机数
            for (int i = 0; i < count-1; i++)
            {
                //定义最大值
                double maxValue = total - count + i - SumArray(result);
                //定义临时结果
                double valuetemp = getRandom(maxValue);
                //装载到结果中,并打印每次的结果
                result[i] = valuetemp;
                Response.Write("第" + (i + 1) + "轮随机出的红包金额为:" + valuetemp + "</br>");
            } 
            Response.Write("第" + count + "轮随机出的红包金额为:" +(total- SumArray(result)) + "</br>");
            result[count-1] = (total - SumArray(result));
            Response.Write("总红包金额:"+SumArray(result));
        }

        //定义指定范围随机数
        #region
        public double getRandom(double end)
        {
            Random ran = new Random();
            double n = Math.Round(ran.NextDouble() * end, 2);
            return n;
        }
        #endregion

        #region 对不定数组求和
        public double SumArray(double[] arr)
        {
            double sum = 0;
            foreach (double m in arr)
            {
                sum += m;
            }
            return sum;
        }
        #endregion
    }
}

运行结果如下所示:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BruceCheng夏夏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值