【问题标题】:C# count the amount of numbers passed in the loopC#计算循环中传递的数字数量
【发布时间】:2017-01-17 20:24:52
【问题描述】:

我目前正在学习 C#,并试图将数字列表打印到控制台行。我想要的列表如下:

01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
etc

我现在面临的唯一问题是在打印 5 个数字后我无法换行。

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++)
            {
                if (i < 10)
                {
                    Console.Write(i.ToString("00 "));
                }
                else
                {
                    Console.Write(i + " ");
                }
            }
            Console.ReadKey();
        }
    }
}

然后打印出来:

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 etc

我怎样才能让每 5 个数字后换行?我必须使用什么样的循环或语句才能让它工作?

【问题讨论】:

  • 只是一个优化——你不需要if (i &lt; 10)...你也可以对>= 10的数字执行Console.Write(i.ToString("00 ")),它会打印你想要的。
  • @entropic,感谢您的优化,我也在代码中实现了这一点:)

标签: c# string for-loop count numbers


【解决方案1】:

重写你的程序如下

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++)
            {
                if (i < 10)
                {
                    Console.Write(i.ToString("00 "));
                }
                else
                {
                    Console.Write(i + " ");
                }
                if (i % 5 == 0) 
                {
                    Console.WriteLine();
                }
            }
            Console.ReadKey();
        }
    }
}

【讨论】:

    【解决方案2】:

    一种常见的方法是检查你刚刚打印的数字是否能被 5 整除,如果能被 5 整除,则打印一个换行符:

    if (i % 5 == 0) {
        Console.WriteLine();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2011-03-05
      相关资源
      最近更新 更多