142
LESSON 11 Using Variables and Performing CalCUlations
Assignment Operators
The assignment operators set a variable (or property or whatever) equal to something else. The
simplest of these is the
= operator, which you have seen several times before. This operator simply
assigns whatever value is on the right to the variable on the left.
The other assignment operators, known as compound assignment operators, combine the variable’s
current value with whatever is on the right in some way. For example, the following code adds
3 to
whatever value
x currently holds:
x += 3;
This has the same effect as the following statement that doesn’t use the += operator:
x = x + 3;
Table 11-7 summarizes these operators. For the examples, assume x is a float and a and b are bools.
TABLE 117
OPERATOR MEANING EXAMPLE MEANS
=
Assign
x = 10; x = 10;
+=
Add and assign
x += 10; x = x + 10;
-=
Subtract and assign
x -= 10; x = x - 10;
*=
Multiply and assign
x *= 10; x = x * 10;
/=
Divide and assign
x /= 10; x = x / 10;
%=
Modulus and assign
x %= 10; x = x % 10;
&=
Logical and and assign
a &= b; a = a & b;
|=
Logical or and assign
a |= b; a = a | b;
^=
Logical xor and assign
a ^= b; a = a ^ b;
Bitwise Operators
The bitwise operators allow you to manipulate the individual bits in integer values. For example, the
bitwise
| operator combines the bits in two values so the result has a bit equal to 1 wherever either
of the two operands has a bit equal to one.
For example, suppose
x and y are the byte values with bits 10000000 and 00000001. Then x | y
has bits 10000001.
These are fairly advanced operators so I’m not going to do much with them, but Table 11-8 summa-
rizes them. The shift operators are not “bitwise” because they don’t compare two operands one bit
at a time, but they are bit-manipulation operators so they’re included here.
596906c11.indd 142 4/7/10 12:32:35 PM
Performing Calculations
143
TABLE 118
OPERATOR MEANING EXAMPLE
&
Bitwise and
11110000
& 00111100
= 00110000
|
Bitwise or
11110000
| 00111100
= 11111100
^
Bitwise xor
11110000
^ 00111100
= 11001100
~
Bitwise complement
~11110000
= 00001111
<<
Left shift
11100111 << 2
= 10011100
>>
Right shift (for signed types)
11100111 >> 2
= 11111001
>>
Right shift (for unsigned types)
11100111 >> 2
= 00111001
If the operand has a signed type (sbyte, int, long), then >> makes new bits on the left copies of the
value’s sign bit (its leftmost bit). If the operand has an unsigned type (
byte, uint, ulong), then >>
makes new bits 0.
All of these except ~ also have corresponding compound assignments operators, for example,
&= and <<=.
Precedence
Sometimes the order in which you evaluate the operators in an expression changes the result. For
example, consider the expression
2 + 3 * 5. If you evaluate the + first you get 5 * 5, which is 25,
but if you evaluate the
*rst you get 2 + 15, which is 17.
To prevent any ambiguity, C# defines operator precedence to determine which comes first.
Table 11-9 lists the major operators in order of decreasing precedence. In other words, the opera-
tors listed near the beginning of the table are applied before those listed later. Operators listed at the
same level have the same precedence and are applied in left-to-right order.
596906c11.indd 143 4/7/10 12:32:35 PM
144
LESSON 11 Using Variables and Performing CalCUlations
TABLE 119
CATEGORY OPERATORS
Primary x++, x--
Unary +, -, !, ++x, --x
Multiplicative *, /, %
Additive +, -
Relational <, <=, >, >=
Equality ==, !=
Logical and
&
Logical xor
^
Logical or
|
Conditional and
&&
Conditional or
||
The compound assignment operators (+=, *=, ^=, and so forth) always have lowest precedence. The
program evaluates the expression on the right, combines it with the original value of the variable on
the left, and then saves the result in that variable.
By carefully using the precedence rules, you can always figure out how a program will evaluate an
expression, but sometimes the expression can be confusing enough to make figuring out the result
difficult. Trying to figure out precedence in confusing expressions can be a great party game (the pro-
grammer’s version of “Pictionary”) but it can make understanding and debugging programs hard.
Fortunately you can always use parentheses to change the order of evaluation, or to make the
default order obvious. For example, consider the following three statements:
x = 2 + 3 * 5;
y = 2 + (3 * 5);
z = (2 + 3) * 5;
The first statement uses no parentheses so you need to use the precedence table to figure out which
operator is applied first. The table shows that
* has higher precedence than + so * is applied first and
the result is
2 + 15, which is 17.
The second statement uses parentheses to emphasize the fact that the
* operator is evaluated first. The
result is unchanged but the code is easier to read.
The third statement uses parentheses to change the order of evaluation. In this case the
+ operator is
evaluated first so the result is
5 * 5, which is 25.
596906c11.indd 144 4/7/10 12:32:36 PM
Try It
145
Parentheses are a useful tool for making your code easier to understand and
debug. Unless an expression is so simple that it’s obvious how it is evaluated,
add parentheses to make the result clear.
CONSTANTS
A constant is a lot like a variable except you must assign it a value when you declare it and you can-
not change the value later.
Syntactically a constant’s declaration is similar to a variable except it uses the keyword
const.
For example, the following code declares a
decimal constant named taxRate and assigns it the
value
0.09M. It then uses the constant in a calculation.
const decimal taxRate = 0.09M;
decimal subtotal = decimal.Parse(subtotalTextBox.Text);
decimal salesTax = taxRate * subTotal;
decimal grandTotal = subTotal + salesTax;
Constants work just like literal values so you could replace the constant taxRate with the literal
value
0.09M in the preceding calculation. Using a constant makes the code easier to read, however.
When you see the value
0.09M, you need to remember or guess that this is a tax rate.
Not only can it be hard to remember what this kind of “magic number” means, but it can also make
changing the value difficult if it appears in many places throughout the program. Suppose the code
uses the value
0.09M in several places. If the sales tax rate went up, you would have to hunt down all
of the occurrences of that number and change them. If you miss some of them, you could get very
confusing results.
Note that constants can contain calculated values as long as C# can perform the calculation before
the program actually runs. For example, the following code declares a constant that defines the
number of centimeters per inch. It then uses that value to define the number of centimeter per foot.
const double cmPerInch = 2.54;
const double cmPerFoot = cmPerInch * 12;
TRY IT
In this Try It you make some simple calculations. You take values entered by the user, convert
them into numbers, do some multiplication and addition, and display the results.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson11 folder in the download.
596906c11.indd 145 4/7/10 12:32:36 PM
146
LESSON 11 Using Variables and Performing CalCUlations
Lesson Requirements
In this lesson, you:
Create the form shown in Figure 11-1.
When the user clicks the Calculate
Button, make
the program:
Multiply each item’s Quantity value by its
Price Each value and display the result in
the corresponding Ext. Price textbox.
Add up the Ext. Price values and display the
result in the Subtotal textbox.
Multiply the Subtotal value by the entered
Tax Rate and display the result in the Sales
Tax textbox.
Add the Subtotal, Sales Tax, and Shipping
values, and display the result in the Grand
Total textbox.
Hints
It is often helpful to perform this kind of calculation in three separate phases:
1. Gather input values from the user and store them in variables.
2. Perform calculations.
3. Display results.
Use the
decimal data type for all of the variables because they represent currency.
Lesson 14 has more to say about manipulating and formatting strings but for this Try It
it’s helpful to know that all data types provide a ToString method that converts a value
into a string. An optional parameter string indicates the format to use. For this Try It, use
the format
“C” (including the quotes) to indicate a currency format, as in:
grandTotalTextBox.Text = grandTotal.ToString(“C”);
Step-by-Step
Create the form shown in Figure 11-1.
1. Create the controls needed for the program shown in Figure 11-1.
a. The Quantity values are NumericUpDown controls.
b. All of the other box-like controls are TextBoxes.
FIGURE 111
596906c11.indd 146 4/7/10 12:32:37 PM
..................Content has been hidden....................

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