寻找一种方法来缩短我的代码

这是我的代码:


    static void Main(string[] args)

    {



        Console.Write("How many tests would you like to do? 1 to 10: ");


        int tests = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine();


    }

有人可以帮我解决我的代码吗?我不知道我在做什么


函数式编程
浏览 124回答 1
1回答

SMILET

制作一个数组int[] counts = new int[13]并使用counts[total]++;; 最后,循环它:for(int i = 2 ; i <= 12 ; i++)&nbsp; &nbsp; // etc(注意:您可以使用 11 个项目的数组并不断处理两个,但是......这可能不值得)就像是:static void Main(){&nbsp; &nbsp; Console.WriteLine("Investigation 1");&nbsp; &nbsp; Console.WriteLine("===============");&nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; Console.Write("How many sets of tests? 1 to 10: ");&nbsp; &nbsp; int sets = Convert.ToInt32(Console.ReadLine());&nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; Random r = new Random();&nbsp; &nbsp; int[] counts = new int[13];&nbsp; &nbsp; for (int ctr = 0; ctr < 36 * sets; ctr++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int a = r.Next(1, 7), b = r.Next(1, 7), total = a + b;&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"Roll {(ctr + 1)}: {a} + {b} = {total}");&nbsp; &nbsp; &nbsp; &nbsp; counts[total]++;&nbsp; &nbsp; }&nbsp; &nbsp; Console.WriteLine("=======================");&nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; Console.WriteLine("Total&nbsp; Expected&nbsp; Actual");&nbsp; &nbsp; Console.WriteLine("=====&nbsp; ========&nbsp; ======");&nbsp; &nbsp; for(int i = 2; i <= 12; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var expected = sets * (6 - Math.Abs(7 - i));&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"&nbsp; {i}&nbsp; &nbsp; &nbsp; &nbsp; {expected}&nbsp; &nbsp; &nbsp; &nbsp; {counts[i]}");&nbsp; &nbsp; }}对于直方图:var maxCount = counts.Max(); // needs "using System.Linq;" at the topfor (int i = 2; i <= 12; i++){&nbsp; &nbsp; var width = ((Console.WindowWidth - 10) * counts[i]) / maxCount; // make it proportional&nbsp; &nbsp; Console.WriteLine($"{i}\t{new string('*', width)}");}
打开App,查看更多内容
随时随地看视频慕课网APP