【问题标题】:How do I display a row of random numbers in C# instead of a column?如何在 C# 中显示一行随机数而不是一列?
【发布时间】:2013-03-24 17:03:48
【问题描述】:

这是程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplicationlotto
{
    class Program
    {
        const int LIMIT = 7;

        static void Main(string[] args)
        {
            int[] lotto = new int[LIMIT];
            int lotDigits;

            Random rnd = new Random();

            foreach (int sub in lotto)
            {
                lotDigits = rnd.Next(0, 8);
                Console.WriteLine(lotDigits);

            }


        }
    }
}

我希望它连续显示 7 个随机数字,形成一个 7 位“乐透号码”,所以它看起来像“5902228”而不是:

5

9

0

2

2

2

8

我尝试使用“0:D7”,它给了我一堆零,最后几位数字是其他数字。

【问题讨论】:

    标签: c# output


    【解决方案1】:

    使用Console.Write 代替Console.WriteLine

    【讨论】:

      【解决方案2】:

      你应该在WriteLine之前创建你期望的string,下面是使用LINQ Enumerable.Rangestring.Join,代码行更少:

      private static void Main(string[] args)
      {
          var random = new Random();
          var numbers = Enumerable.Range(0, 7)
                                  .Select(x => random.Next(0, 9));
      
          var output = string.Join(string.Empty, numbers);
      
          Console.WriteLine(output);
      }
      

      或者使用Aggregate:

      var output = Enumerable.Range(0, 7)
                             .Aggregate(string.Empty, 
                                     (str, i) => str += random.Next(0, 9));
      

      【讨论】:

        【解决方案3】:

        使用Console.Write 代替Console.WriteLine

        Console.WriteLine - 在控制台窗口中添加一个额外的行,因此每个数字出现在不同的行中。

        foreach (int sub in lotto)
        {
            lotDigits = rnd.Next(0, 8);
            Console.Write(string.Format("{0}\t", lotDigits));
        }
        

        您应该将数字分开,以免它们看起来像是一个单独的数字。

        【讨论】:

          【解决方案4】:
          foreach (int sub in lotto)
          {
                  lotDigits = rnd.Next(0, 8);
                  Console.Write(string.Format("{0} ", lotDigits));
          }
          

          【讨论】:

            猜你喜欢
            • 2020-08-14
            • 2020-08-19
            • 1970-01-01
            • 2021-12-23
            • 2020-05-18
            • 1970-01-01
            • 2021-11-30
            • 1970-01-01
            • 2020-08-17
            相关资源
            最近更新 更多