1

这是程序:

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”,它给了我一堆零,最后几位数字是其他数字。

4

4 回答 4

4

使用Console.Write代替Console.WriteLine

于 2013-03-24T17:04:42.287 回答
2

您应该string在之前创建您的预期WriteLine,下面是使用 LINQEnumerable.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));
于 2013-03-24T17:12:22.730 回答
0

使用Console.Write代替 Console.WriteLine

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

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

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

于 2013-03-24T17:05:19.417 回答
0
foreach (int sub in lotto)
{
        lotDigits = rnd.Next(0, 8);
        Console.Write(string.Format("{0} ", lotDigits));
}
于 2013-03-24T17:06:05.143 回答