Performing Calculations
137
Operands and Operators
One issue that confuses some people is the fact that C# uses the data types of an expressions operands
to determine the way the operators work. If an expression contains two integers, the operators use
integer arithmetic. If an expression contains two floats, the operators use floating-point arithmetic.
Sometimes this can lead to confusing results. For example, the following code tries to save the
value 1/7 in the
float variable ratio. The values 1 and 7 are integers so this calculation uses
integer division, which discards any remainder. Because 1 / 7 = 0 with a remainder of 1,
ratio is
assigned the value 0, which is probably not what you intended.
float ratio = 1 / 7;
To force C# into using floating-point division, you can convert the numbers into the float data
type. The following code uses the
F sufx character to indicate that 1 and 7 should have the float
data type instead of
int. Now the program performs floating-point division so it assigns ratio the
value 0.142857149 (approximately).
float ratio = 1F / 7F;
Instead of using data type prefixes, you can also use casting to make the program treat the values as
floats as in the following code:
float ratio = (float)1 / (float)7;
Promotion
If an expression uses two different data types, C# promotes the one with the more restrictive type.
For example, if you try to divide an
int by a float, C# promotes the int to a float before it per-
forms the division.
The following code divides a
float by an int. Before performing the calculation, C# promotes the
value 7 to a
float. This is sometimes called implicit casting. The code then performs the division
and saves the result 0.142857149 in the variable
ratio.
float ratio = 1F / 7;
Operator Summary
C# has many operators for manipulating variables of different data types. The following sections
describe the most commonly used operators grouped by operand type (arithmetic, string, logical,
and so forth).
Remember that some operators behave differently depending on the data types of their operands.
Arithmetic Operators
The arithmetic operators perform calculations on numbers. Table 11-4 summarizes these opera-
tors. The Example column shows sample results. For the nal examples, assume that
x is an int
that initially has value
10.
596906c11.indd 137 4/7/10 12:32:33 PM
138
LESSON 11 Using Variables and Performing CalCUlations
TABLE 114
OPERATOR MEANING EXAMPLE
+
Addition 3 + 2 is 5
-
Negation - 3 is -3
-
Subtraction 3 - 2 is 1
*
Multiplication 3 * 2 is 6
/
Division (integer) 3 / 2 is 1
/
Division (floating point) 3F / 2F is 1.5
%
Modulus 3 % 2 is 1
++
Pre-increment ++x: x is incremented to 11 and then the statement
uses the new value 11
++
Post-increment x++: the statement uses the current value of x (10) and
then
x is incremented to 11
--
Pre-decrement --x: x is decrements to 9 and then the statement uses
the new value 9
--
Post-decrement x--: the statement uses the current value of x (10) and
then
x is decremented to 9
Integer division drops any remainder and returns the integer quotient. The modulus operator
does the opposite: it drops the quotient and returns the remainder. For example,
17 % 5 returns 2
because
17 divided by 5 is 3 with a remainder of 2.
The pre- and post- increment and decrement operators return a value either before or after it is
incremented or decremented. For example, the following code sets
x equal to 10 + y = 20 and then
adds
1 to y. When the code finishes, x = 20 and y = 11;
int x, y = 10;
x = 10 + y++;
In contrast, the following code increments y first and then uses the new value to calculate x. When
this code finishes,
x = 21 and y = 11.
int x, y = 10;
x = 10 + ++y;
The decrement operators work similarly except they subtract 1 instead of adding 1.
The increment and decrement operators can be very confusing, particularly when theyre in the
middle of a complex expression. If you have trouble with them, simply avoid them. For example,
596906c11.indd 138 4/7/10 12:32:34 PM
Performing Calculations
139
the following code gives you the same result as the previous code but without the pre-increment
operator:
int x, y = 10;
y = y + 1;
x = 10 + y;
Logical Operators
The logical operators perform calculations on Boolean (true or false) values. They let you com-
bine logical statements to form new ones.
Lesson 18 explains how to use these values to perform tests that let a program take action only
under certain circumstances. For example, a program might pay an employee overtime if the
employee is hourly and worked more than 40 hours in the last week.
Table 11-5 summarizes these operators.
TABLE 115
OPERATOR MEANING
&
And
|
Or
^
Xor
!
Not
&&
Conditional And
||
Conditional Or
The & operator returns true if and only if both of its operands are true. For example, you must buy
lunch if it’s lunch time and you forgot to bring a lunch today:
mustBuyLunch = isLunchTime & forgotToBringLunch;
The | operator returns true if either of its operands is true. For example, you can afford lunch if
you either brought enough money or you have a credit card (or both):
canAffordLunch = haveEnoughMoney | haveCreditCard;
The ^ operator is perhaps the most confusing. It returns true if one of its operands is true and the
other is
false. For example, you and Ann will get a single lunch check and pay each other back
later if either Ann forgot her money and you brought yours, or Ann remembered her money and you
forgot yours. If neither of you forgot your money, you can get separate checks. If you both forgot
your money, youre both going hungry today.
singleCheck = annForgotMoney ^ youForgotMoney;
596906c11.indd 139 4/7/10 12:32:34 PM
140
LESSON 11 Using Variables and Performing CalCUlations
The ! operator returns true if its single operand is false. For example, if the cafeteria is not closed,
you can have lunch there:
canHaveLunch = !cafeteriaIsClosed;
The conditional operators, which are also called short-circuit operators, work just like the regular
ones except they don’t evaluate their second operand unless they must. For example, consider the
following “and” statement:
mustBuyLunch = isLunchTime && forgotToBringLunch;
Suppose it’s only 9:00 a.m. so isLunchTime is false. When the program sees this expression, evalu-
ates
isLunchTime, and sees the && operator, it already knows that mustBuyLunch must be false no
matter what value follows the
&& (in this case forgotToBringLunch), so it doesn’t bother to evaluate
forgotToBringLunch and that saves a tiny amount of time.
Similarly, consider the following “or” statement:
canAffordLunch = haveEnoughMoney | haveCreditCard;
If you have enough money, haveEnoughMoney is true, so the program doesn’t need to evaluate
haveCreditCard to know that the result canAffordLunch is also true.
Because the conditional
&& and || operators are slightly faster, most developers use them when they
can instead of
& and |.
There is one case where the conditional operators may cause problems. If the
second operand is not a simple value but is the returned result from some sort
of method call, then if you use a conditional operator, you cannot always know
whether the method was called. This might matter if the method has side effects:
consequences that last after the method has finished like opening a database or
creating a file. In that case, you cannot know later whether the database is open
or the file is created so the code might become confused.
This is seldom a problem and you can avoid it completely by avoiding side effects.
String Operators
The only string operator C# provides is +. This operator concatenates (joins) two strings together.
For example, suppose the variable
username contains the users name. Then the following code con-
catenates the text “Hello ” (note the trailing space) with the user’s name and displays the result in a
message box:
MessageBox.Show(“Hello “ + username);
Lesson 14 explains methods that you can use to manipulate strings: find substrings, replace text,
check length, and so forth.
596906c11.indd 140 4/7/10 12:32:34 PM
Performing Calculations
141
One very non-obvious fact about string operations is that a string calculation
does not really save the results in the same memory used by the variable on the
left of an assignment statement. Instead it creates a new string holding the result
of the calculation and makes the variable refer to that.
For example, consider the following code.
string greeting = usernameTextBox.Text;
greeting = “Hello “ + username;
This code looks like it saves a user’s name in variable username and then tacks
“Hello” onto the front. Actually the second statement creates a whole new
string that holds “Hello” plus the user’s name and then makes
greeting refer
to the new string.
For many practical applications, the difference is small, and you can ignore
it. However, if you’re performing many concatenations (perhaps in one of
the loops described in Lesson 19), then your program may have performance
issues. The
StringBuilder class can help address this issue, but its a bit
more advanced so Im not going to cover it here. See
msdn.microsoft.com/
library/2839d5h5.aspx
for more information.
Comparison Operators
The comparison operators compare two values and return true or false depending on the values’
relationship. For example,
x < y returns true if x is less than y.
Table 11-6 summarizes these operators.
TABLE 116
OPERATOR MEANING EXAMPLE
==
Equals 2 == 3 is false
!=
Not equals 2 != 3 is true
<
Less than 2 < 3 is true
<=
Less than or equal to 2 <= 3 is true
>
Greater than 2 > 3 is false
>=
Greater than or equal to 2 >= 3 is false
596906c11.indd 141 4/7/10 12:32:35 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.76.44