亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

尋找一種方法來縮短我的代碼

尋找一種方法來縮短我的代碼

C#
函數式編程 2021-06-03 11:32:50
這是我的代碼:    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();    }有人可以幫我解決我的代碼嗎?我不知道我在做什么
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

制作一個數組int[] counts = new int[13]并使用counts[total]++;; 最后,循環它:


for(int i = 2 ; i <= 12 ; i++)

    // etc

(注意:您可以使用 11 個項目的數組并不斷處理兩個,但是......這可能不值得)


就像是:


static void Main()

{


    Console.WriteLine("Investigation 1");

    Console.WriteLine("===============");

    Console.WriteLine();

    Console.Write("How many sets of tests? 1 to 10: ");


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

    Console.WriteLine();


    Random r = new Random();

    int[] counts = new int[13];


    for (int ctr = 0; ctr < 36 * sets; ctr++)

    {

        int a = r.Next(1, 7), b = r.Next(1, 7), total = a + b;

        Console.WriteLine($"Roll {(ctr + 1)}: {a} +  = {total}");

        counts[total]++;

    }


    Console.WriteLine("=======================");

    Console.WriteLine();

    Console.WriteLine("Total  Expected  Actual");

    Console.WriteLine("=====  ========  ======");


    for(int i = 2; i <= 12; i++)

    {

        var expected = sets * (6 - Math.Abs(7 - i));

        Console.WriteLine($"  {i}        {expected}        {counts[i]}");

    }

}

對于直方圖:


var maxCount = counts.Max(); // needs "using System.Linq;" at the top

for (int i = 2; i <= 12; i++)

{

    var width = ((Console.WindowWidth - 10) * counts[i]) / maxCount; // make it proportional

    Console.WriteLine($"{i}\t{new string('*', width)}");

}


查看完整回答
反對 回復 2021-06-05
  • 1 回答
  • 0 關注
  • 151 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號