You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中通过方法实现自定义面数的骰子随机掷骰功能

问题分析与解决方案

核心问题

你的RollDice方法中有一行致命代码直接破坏了参数传递:

amountSides = 0;

这行代码会把从Main方法传入的自定义骰子面数直接清零,导致后续调用randomObject.Next(1, amountSides)时,传入的范围是(1, 0)——这违反了Random.Next的参数规则(maxValue必须大于minValue),不仅无法生成有效随机数,还会抛出ArgumentOutOfRangeException。

另外,Random.Next(minValue, maxValue)返回的是大于等于minValue、小于maxValue的整数,所以如果要生成1到amountSides的骰子数,需要把第二个参数设为amountSides + 1,否则最多只能生成到amountSides - 1。

修正后的代码

修正RollDice方法

static int RollDice(Random randomObject, int amountSides)
{
    // 移除覆盖参数的错误代码
    // amountSides = 0;
    
    // 生成1到amountSides的随机数(包含两端)
    return randomObject.Next(1, amountSides + 1);
}

完整修正后的控制台程序

namespace ConsoleApp3
{
    class Program
    {
        static int RollDice(Random randomObject, int amountSides)
        {
            return randomObject.Next(1, amountSides + 1);
        }

        static void Main()
        {
            Random random = new Random(); 
            List<int> dices = new List<int>();

            Console.WriteLine("\n\tWelcome to the dice generator!");

            bool run = true;
            while (run)
            {
                Console.WriteLine("\n\t[1] Roll dice\n" +
                    "\t[2] Check what you rolled\n" +
                    "\t[3] Quit");
                Console.Write("\tChoose: ");
                int choice;
                int.TryParse(Console.ReadLine(), out choice);
                switch (choice)
                {
                    case 1:
                        Console.Write("\n\tHow many dices do you want to roll: ");
                        bool amountValid = int.TryParse(Console.ReadLine(), out int amount);
                        
                        Console.Write("\n\tHow many sides do the dices have:  ");
                        bool sidesValid = int.TryParse(Console.ReadLine(), out int amountSides);

                        // 新增输入合法性校验:骰子数量>0,面数>=2
                        if (amountValid && sidesValid && amount > 0 && amountSides >= 2)
                        {
                            for (int i = 0; i < amount; i++)
                            {
                                dices.Add(RollDice(random, amountSides));
                            }
                            Console.WriteLine($"\n\tRolled {amount} {amountSides}-sided dice successfully!");
                        }
                        else
                        {
                            Console.WriteLine("\n\tInvalid input: Please enter positive integers, and dice must have at least 2 sides.");
                        }
                        break;
                    case 2:
                        int sum = 0;
                        if (dices.Count <= 0)
                        {
                            Console.WriteLine("\n\tThere are no saved dice rolls! ");
                        }
                        else
                        {
                            Console.WriteLine("\n\tRolled dice: ");
                            foreach (int dice in dices)
                            {
                                Console.WriteLine("\t" + dice);
                                sum += dice;
                            }
                            // 使用(double)避免整数除法导致的平均值失真
                            Console.WriteLine($"\n\tAverage of rolled dices: {(double)sum / dices.Count:F2}");
                        }
                        break;
                    case 3:
                        Console.WriteLine("\n\tThank you for rolling dice");
                        System.Threading.Thread.Sleep(1000);
                        run = false;
                        break;
                    default:
                        Console.WriteLine("\n\tChoose 1-3 from the menu");
                        break;
                }
            }
        }
    }
}

额外优化说明

  1. 输入校验增强:替换Convert.ToInt32为int.TryParse,避免输入非数字时抛出异常;同时增加骰子数量>0、面数>=2的校验,确保输入有效。
  2. 平均值计算优化:将sum转为double后再做除法,避免整数除法导致的平均值精度丢失(比如总和为5、数量为2时,整数除法得到2,而实际平均是2.5)。
  3. 用户反馈增强:掷骰子成功后增加提示信息,让用户明确操作结果。

内容的提问来源于stack exchange,提问作者blaeck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:55:21