如何在15个数字中找到最大的数字?

时间:2019-10-14 16:48:22

标签: vb.net

对于一份计算机科学作业,我需要随机生成15个数字,将它们相互比较,然后输出最大的数字。但是,当我尝试将其与最大变量进行比较时,并非始终都是100%正确的。有人可以帮助我获得100%的准确性。

        Dim largest As Integer
        Dim random As New Random()
        Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o As Integer

        Console.WriteLine("This program will generate 15 numbers and print the largest of them.")


        a = random.Next(0, 100)
        Console.WriteLine(a)
        b = random.Next(0, 100)
        Console.WriteLine(b)
        c = random.Next(0, 100)
        Console.WriteLine(c)
        d = random.Next(0, 100)
        Console.WriteLine(d)
        e = random.Next(0, 100)
        Console.WriteLine(e)
        f = random.Next(0, 100)
        Console.WriteLine(f)
        g = random.Next(0, 100)
        Console.WriteLine(g)
        h = random.Next(0, 100)
        Console.WriteLine(h)
        i = random.Next(0, 100)
        Console.WriteLine(i)
        j = random.Next(0, 100)
        Console.WriteLine(j)
        k = random.Next(0, 100)
        Console.WriteLine(k)
        l = random.Next(0, 100)
        Console.WriteLine(l)
        m = random.Next(0, 100)
        Console.WriteLine(m)
        n = random.Next(0, 100)
        Console.WriteLine(n)
        o = random.Next(0, 100)
        Console.WriteLine(o)

        If a > b Then
            largest = a
        ElseIf b > largest Then
            largest = b
        ElseIf c > largest Then
            largest = c
        ElseIf d > largest Then
            largest = d
        End If

        Console.WriteLine("The biggest number is " & largest)



        Console.ReadLine()

1 个答案:

答案 0 :(得分:1)

这是做事的一种简单方法

Dim rand = New Random()
Dim numbers = Enumerable.Range(0, 15).Select(Function(i) rand.Next(0, 100))
For Each number In numbers
    Console.WriteLine(number)
Next
Console.WriteLine($"The biggest number is {numbers.Max()}")

它使用IEnumerable(Of Integer)来保存值,而不是单个变量。它首先使用Enumerable.Range()创建值1至15(这些值并不重要),然后使用Enumerable.Select()将其转换为随机值。然后,它使用Enumerable.Max来获取最大值。

这也可以解决问题,但是它不使用内置的Enumerable函数,因此可以更轻松地将其作为家庭作业传递出去。

Dim rand = New Random()
Dim max = Integer.MinValue
For i = 1 To 15
    Dim number = rand.Next(0, 100)
    If max < number Then max = number ' this is probably what the teacher is looking for!
    Console.WriteLine(number)
Next
Console.WriteLine($"The biggest number is {max}")