【问题标题】:Printing out 3 elements in array per line每行打印出数组中的 3 个元素
【发布时间】:2011-09-15 20:30:39
【问题描述】:

我有一个包含 x 个元素的数组,并且想要打印出每行三个元素(使用 for 循环)。

例子:

123    343    3434
342    3455   13355
3444   534    2455

我想我可以使用 %,但我就是不知道该怎么做。

【问题讨论】:

  • 向我们展示您尝试过的代码。另外,如果这是家庭作业,让我们这样标记它。是吗?
  • 啊,对不起。我会去做的。这只是大代码中的最后一件事,我没有任何代码可以显示。

标签: c# arrays loops


【解决方案1】:

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   

【讨论】:

    【解决方案2】:

    一次循环遍历数组 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 整除,则必须添加一些逻辑以确保在最终循环中不会超出范围。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        长...但带有 cmets:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-15
          • 2013-07-16
          • 1970-01-01
          • 1970-01-01
          • 2021-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多