繁体   English   中英

每行打印出3个元素

[英]Printing out 3 elements in array per line

我有一个包含x个元素的数组,并希望每行打印出三个元素(带有for循环)。

例:

123    343    3434
342    3455   13355
3444   534    2455

我想我可以使用%,但我无法弄清楚如何做到这一点。

For循环更合适:

var array = Enumerable.Range(0, 11).ToArray();
for (int i = 0; i < array.Length; i++)
{
    Console.Write("{0,-5}", array[i]);
    if (i % 3 == 2)
        Console.WriteLine();
}

输出:

0    1    2
3    4    5
6    7    8
9    10   

一次循环遍历数组3并使用String.Format()

这应该做到......

for (int i = 0; i < array.Length; i += 3)
    Console.WriteLine(String.Format("{0,6} {1,6} {2,6}", array[i], array[i + 1], array[i + 2]));

但是如果数组中的项数不能被3除,那么你必须添加一些逻辑以确保你不会在最后一个循环中超出范围。

您可能需要修复格式间距...

for(int i=0;i<array.Length;i++)
{
    Console.Write(array[i] + " ");
    if((i+1)%3==0)
        Console.WriteLine(); 
}

很长......但有评论:

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = list.Count;
int numGroups = list.Count / 3 + ((list.Count % 3 == 0) ? 0 : 1); // A partially-filled group is still a group!
for (int i = 0; i < numGroups; i++)
{
     int counterBase = i * 3;
     string s = list[counterBase].ToString(); // if this a partially filled group, the first element must be here...
     if (counterBase + 1 < count) // but the second...
          s += list[counterBase + 1].ToString(", 0");
     if (counterBase + 2 < count) // and third elements may not.
          s += list[counterBase + 2].ToString(", 0");
     Console.WriteLine(s);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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