Reputation: 7
For a piece of computer science homework, I need to randomly generated 15 numbers, compare them all to each other and then output the biggest. But when I try to compare it to the largest variable it isnt 100% correct all the time. Can someone help me to get it 100% accuracy.
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()
Upvotes: 0
Views: 98
Reputation: 15774
Here is a simpler way to do what you're doing
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()}")
It uses an IEnumerable(Of Integer) to hold the values, instead of individual variables. It first uses Enumerable.Range() to create values 1 to 15 (these are not important) then converts them into random values with Enumerable.Select(). It then uses Enumerable.Max to get the maximum value.
This will also do the trick, however it doesn't use built in Enumerable functions, which might make it easier to pass it off as your own homework.
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}")
Upvotes: 1