# Program always displaying 1 variable

• ### Question

• For some reason, this always outputs Number 3, no matter what. Any fixes?

[code]

If num1 > num2 And num3 Then
largest = "Number 1"
ElseIf num2 > num1 And num3 Then
largest = "Number 2"
Else
largest = "Number 3"
EndIf

If num1 < num2 And num3 Then
smallest = "Number 1"
ElseIf num2 < num1 And num3 Then
smallest = "Number 2"
Else
smallest = "Number 3"
EndIf

TextWindow.WriteLine("The largest number was: "+largest)
TextWindow.WriteLine("The smallest number was: "+smallest)

[/code]

Saturday, September 27, 2014 12:14 PM

• The problem is how you do the if conditions:

Look at this "If num1 > num2 And num3 Then"

• Each condition must evaluate to true or false
• Conditions can be combined logically with Or or And

So the syntax is:

If condition1 And condition2 Then

So in your case condition1 num1 > num2 may be true or false - OK

But condition2 num3 is not true - the only way a variable can be true is if it is equal to "True" and is therefore false and the whole statement is false and eventaully you get the final else (number3).

So the fix - properly formed conditions:

If (num1 > num2 And num1 > num3) Then
largest = "Number 1"
ElseIf (num2 > num3) Then 'Note we don't really need to check if num2 > num1
largest = "Number 2"
Else
largest = "Number 3" 'This will also catch cases where the values are equal
EndIf

• Edited by Saturday, September 27, 2014 12:56 PM
• Marked as answer by Saturday, September 27, 2014 1:21 PM
Saturday, September 27, 2014 12:31 PM

### All replies

• The problem is how you do the if conditions:

Look at this "If num1 > num2 And num3 Then"

• Each condition must evaluate to true or false
• Conditions can be combined logically with Or or And

So the syntax is:

If condition1 And condition2 Then

So in your case condition1 num1 > num2 may be true or false - OK

But condition2 num3 is not true - the only way a variable can be true is if it is equal to "True" and is therefore false and the whole statement is false and eventaully you get the final else (number3).

So the fix - properly formed conditions:

If (num1 > num2 And num1 > num3) Then
largest = "Number 1"
ElseIf (num2 > num3) Then 'Note we don't really need to check if num2 > num1
largest = "Number 2"
Else
largest = "Number 3" 'This will also catch cases where the values are equal
EndIf

• Edited by Saturday, September 27, 2014 12:56 PM
• Marked as answer by Saturday, September 27, 2014 1:21 PM
Saturday, September 27, 2014 12:31 PM
• Thanks :D Worked like a charm. Looks like I'll need to learn that efficient way of doing it...
Saturday, September 27, 2014 1:21 PM