lundi 25 mai 2015

How to properly align a 5x10 2-d array with random data in console?

First time poster here, but I have been using stackoverflow this entire quarter to help me along in my intro to C# class. Generally, I can find what I'm looking for if I look hard enough, but I have been unable to find anyone that has already answered my question.

I have an assignment that wants me to display random numbers in a 5x10 array. I then need to calculate the sum of the numbers and the average, but I'll worry about that later.

Randomized numbers should be <0 and <=100. The console output should look something like this

x  x  x  x  x
x  x  x  x  x
x  x  x  x  x
x  x  x  x  x
x  x  x  x  x

just with 10 rows instead of 5.

However, my current code is listing the random numbers next to each other and wrapping lines once it reaches the end of the line like this

x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
x  x  x  x ...etc

What can I do to get it to align correctly? I have pretty much exhausted my ability to use format modifiers, so when you see {0, 5}, that's just my most recent attempt, but far from my only. I'm extremely new to C#, so any advanced techniques would be out of the question, as I wouldn't understand how to properly use them. Any thoughts S.O.?!

using System;

namespace DilleyHW7
{
    class Array2d
    {
        static void Main()
        {
            const int ROWS = 10;
            const int COLS = 5;
            const int MAX = 100;
            int[,] numbers = new int[10, 5];

            Random rand = new Random();

            for (int i = 0 ; i< ROWS; ++i)
            {
                for (int j = 0; j < COLS; ++j)
                {
                    numbers[i, j] = rand.Next(0, 101);
                    Console.Write(" {0, 5}", numbers[i, j]);
                }
            }
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire