C#数组打印

本文关键字:打印 数组 | 更新日期: 2023-09-27 18:05:35

我正在努力实现以下目标:

用户输入100个数字,然后将数字打印在3列中

到目前为止,这就是我所拥有的,它可以工作,但不会打印数组的最后一个值。

我做错了什么?

    static void Main(string[] args)
    {
        int digit = 0;
        const int LIMIT = 100;
        int[] row = new int[LIMIT];
        for (int i = 0; i < row.Length; i++)
        {
            Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
            digit = int.Parse(Console.ReadLine());
            row[i] = digit;
        }
        for (int i = 0; i < row.Length - 2; i+=3)
        {               
           Console.WriteLine(row[i] + "'t" + row[i + 1] + "'t" + row[i + 2]);
        }
    }

C#数组打印

使用此打印代替

for (int i = 0; i < row.Length; i++)
{
   Console.Write(row[i] + "'t");
   if (i % 3 == 2)
       Console.WriteLine();
}

您的问题是,您不能简单地使用Console.Write,并尝试一次性写入行。

事实上,在这里使用StringBuilder会更干净。

更换

for (int i = 0; i < row.Length - 2; i+=3)
{               
   Console.WriteLine(row[i] + "'t" + row[i + 1] + "'t" + row[i + 2]);
}

通过

StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < row.Length; i++)
{
    count++;
    if (count == 3)
    {
        sb.AppendLine(row[i])
        count = 0;
    }
    else
        sb.Append(row[i]).Append(''t');
}
Console.WriteLine(sb.ToString());

我认为这很明确,但如果你需要澄清,请随时询问。当然,这里count的使用非常学者,一个真正的程序可以使用%运算符,就像其他答案中所示的那样。

for循环中存在错误条件。如果你不介意LINQ,你可以使用以下工具:

foreach (string s in row.Select((n, i) => new { n, i })
                        .GroupBy(p => p.i / 3)
                        .Select(g => string.Join("'t", g.Select(p => p.n))))
    Console.WriteLine(s);

如果你对LINQ不满意,你可以这样做:

int colIndex = 0;
foreach (int n in row)
{
    Console.Write(n);
    if (colIndex == 2)
        Console.WriteLine();
    else
        Console.Write(''t');
    colIndex = (colIndex + 1) % 3;
}

jonavo是正确的。96+3=99之后并且您已经完成了row.length-2,请将其更改为row。长度+2。并且在打印中不打印if the i+1 or I+2 >= max

它不打印它,因为100不能被3整除,并且for循环在每次迭代中都会将变量增加3,所以最后一个元素将被跳过。

也许这是在循环之后:

int rest = row.Length % 3;
if(rest > 0)
   Console.WriteLine(row[row.Length - rest] + "'t" + row.ElementAtOrDefault(row.Length - rest + 1));

这是因为您的索引。您的运行索引i来自

0,      3,      6,      9,       ...   96,       99

因此,这将输出阵列位置:

0,1,2   3,4,5   6,7,8   9,10,11  ...   96,97,98  99,100,101 (index out of bounds)
row.Length equals 100, so your loop-condition (i < row.Length - 2) is correct, but even better would be (i < row.Length - 3).

所以你的问题是如何打印最后一个数字。。。你看,你有3列100位数字。这一共有33行,剩下一位数字。

也许你只需要添加一些Console.WriteLine(row[row.Length-1]);就可以了。

看起来您有很多选择。这里有一种使用嵌套循环的方法:

int numCols = 3;
for (int i = 0; i < row.Length; i += numCols)
{               
    for (int j = i; j < i + numCols && j < row.Length; j++)
    {
        Console.Write(row[j] + "'t");
    }
    Console.WriteLine();
}

试试这个代码。

使用此循环,您还可以在不更改代码的情况下更改行数/列数。此外,使用临时缓冲区,一次向控制台输出整行。

    static void Main(string[] args)
    {
        int digit = 0;
        const int LIMIT = 10;
        const int COLS = 3;
        int[] row = new int[LIMIT];
        for (int i = 0; i < row.Length; i++)
        {
            Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
            // Re-try until user insert a valid integer.
            while (!int.TryParse(Console.ReadLine(), out digit))
                Console.WriteLine("Wrong format: please insert an integer number:");
            row[i] = digit;
        }
        PrintArray(row, COLS);
        // Wait to see console output.
        Console.ReadKey();
    }
    /// <summary>
    /// Print an array on console formatted in a number of columns.
    /// </summary>
    /// <param name="array">Input Array</param>
    /// <param name="columns">Number of columns</param>
    /// <returns>True on success, otherwise false.</returns>
    static bool PrintArray(int[] array, int columns)
    {
        if (array == null || columns <= 0)
            return false;
        if (array.Length == 0)
            return true;
        // Build a buffer of columns elements.
        string buffer = array[0].ToString();
        for (int i = 1; i < array.Length; ++i)
        {
            if (i % columns == 0)
            {
                Console.WriteLine(buffer);
                buffer = array[i].ToString();
            }
            else
                buffer += "'t" + array[i].ToString();
        }
        // Print the remaining elements
        if (array.Length % columns != 0)
            Console.WriteLine(buffer);
        return true;
    }

只是为了完整性

请注意,如果键入了意外字符,int.Parse(Console.ReadLine())可能引发异常。最好使用此处所述的int.TryParse()。这个方法不会抛出异常,而是返回一个布尔值,报告成功的转换。

while (!int.TryParse(Console.ReadLine(), out digit))
    Console.WriteLine("Wrong format: please insert an integer number:");

这段代码告诉用户,键入的字符串不能被解释为整数,并在转换成功之前再次提示。