《零基础学C#》第六章-实例03:模拟微信红包——练习2

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wtxhai/article/details/88638679
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example603_02
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("—————————模拟微信抢红包—————————\n");
            Console.Write("请输入要装入红包的总金额(元):");
            double total = Convert.ToDouble(Console.ReadLine());  //输入“红包的总金额”
            Console.Write("请输入红包的个数(个):");
            int bagsnum = Convert.ToInt32(Console.ReadLine());    //输入“红包的个数”
            double min = 0.01;                                    //初始化“红包的最小金额”
            Random random = new Random(); //创建随机数对象Random
            for (int i = 1; i < bagsnum; i++)
            { //设置“循环”
                double safe = (total - (bagsnum - i) * min) / (bagsnum - i); //通过公式模拟数学中的离散模型
                double money = (double)random.Next((int)((safe - min) * 100)) / 100 + min; //根据离散模型得到每个红包的金额
                total = total - money; //替换total的值
                Console.WriteLine("第" + i + "个红包:{0:C}元", money); //输出结果
            }
            Console.WriteLine("第" + bagsnum + "个红包:{0:C}元", total); //输出结果
            Console.ReadLine();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wtxhai/article/details/88638679