COMPARISON OPERATORS


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.

Table 6.1: Visual C++ Comparison Operators

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.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net