在运行以下程序后,lownum保持为0。如果不输入任何负数,则完全有意义。但是,如果输入了所有正数,我如何选择获得最低的数字。
Sub Main()
Declaring variables
Dim number1 As Integer = 0
Dim number2 As Integer = 0
Dim lownum As Integer
Dim highnum As Integer
'For statement to run loop 10 times
For counter As Integer = 1 To 10
'Prompting user to enter two numbers
Console.Write("Enter the first number: ")
number1 = Console.ReadLine
Console.Write("Enter the second number: ")
number2 = Console.ReadLine
'If statements to determine and keep track of highest and lowest number
If number1 > number2 Then
Console.WriteLine("Number 1 is larger " & number1)
ElseIf number2 > number1 Then
Console.WriteLine("Number 2 is larger " & number2)
Else
Console.WriteLine("The two numbers are equal: " & number1 & " " & number2)
End If
If number1 > highnum Then
highnum = number1
End If
If number1 < lownum Then
lownum = number1
End If
If number2 > highnum Then
highnum = number2
End If
If number2 < lownum Then
lownum = number2
End If
Next
'Displaying highest and lowest numbers
Console.WriteLine("The highest number entered was " & highnum)
Console.WriteLine("The lowest number entered was " & lownum)
'Prompting user for input to continue
Console.WriteLine("Press any key to continue: ")
Console.ReadKey()
End Sub
答案 0 :(得分:1)
只需检查您的counter
变量。如果为1,则将您的值设置为高和低。如果大于1,则进行比较:
For counter As Integer = 1 To 10
' ... other code ...
If counter = 1 Then
lownum = Math.Min(number1, number2)
highnum = Math.Max(number1, number2)
Else
lownum = Math.Min(lownum, Math.Min(number1, number2))
highnum = Math.Max(highnum, Math.Max(number1, number2))
End If
Next
答案 1 :(得分:0)
您测试的值是小于还是小于两个起始变量0。
如果您不提供最小值/最大值并且不输入值<0或> 0,则永远不会设置“最小值/最大值”。
因此,您要将它们设置为最大允许值和最小允许值。
通过最小/最大值的初始化将变量声明为此,您的代码应该可以正常工作。
Dim number1 As Integer = 0
Dim number2 As Integer = 0
Dim lownum As Integer = Integer.MaxValue
Dim highnum As Integer = Integer.MinValue