简体   繁体   中英

Looking for a way to shorten my code

This is my code:

    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();

    }

can someone help me out with my code please? i have no idea what im doing

Thanks

Make an array int[] counts = new int[13] and just use counts[total]++; ; at the end, loop over it:

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

(note: you could use an array of 11 items and constantly handle the off-by-two, but... it probably isn't worth it)


Something like:

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} + {b} = {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]}");
    }
}

For a histogram:

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)}");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM