Many of the conditional logic tests featured in the chapter games and examples so far have involved comparing two values or expressions to see if they are equal. Although this is certainly a useful type of test, you often need to test the relationship between values and expressions in different ways. For example, you might want to know if one value is less than, greater than, or equal to another value. To accomplish these types of comparisons, you can use any of the comparison operators listed in Table 6.1.
Operator | Description |
---|---|
== | Equal |
!= | Not equal |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
To gain a better sense of how to use these operators, study the following example:
Int32 intSecretNumber = 6; Int32 intPlayerGuess = 10; if( intPlayerGuess < intSecretNumber ) MessageBox::Show("Your guess is too low."); if( intPlayerGuess == intSecretNumber ) MessageBox::Show("Your guess is correct."); if( intPlayerGuess > intSecretNumber ) MessageBox::Show("Your guess is too high.");
In this example, three if statements have been established to test two values against one another. The first if statement uses the less than operator (<) to see if intPlayerGuess (which is 10) is less than intSecretNumber (which is 6). The second if statement checks to see if the player's guess is equal to intSecretNumber. Finally, the third if statement uses the greater than operator (>) to determine whether the number supplied by the user is greater than intSecretNumber. In this example, the message informing the player that his guess is too high activates because 10 is greater than 6.