📄 c++ for dummys.txt
字号:
value of celsius is whatever the user enters there.
Calculating Expressions
All but the most basic programs perform calculations of one type or another.
In C++, an expression is a statement that performs a calculation. Said another
way, an expression is a statement that has a value. An operator is a command
that generates a value.
For example, in the Conversion example program — specifically in the two
lines marked as a calculation expression — the program declares a vari
able factor and then assigns it the value resulting from a calculation. This par
ticular command calculates the difference of 212 and 32; the operator is the
minus sign (–), and the expression is 212–32.
26 Part I: Introduction to C++ Programming
Storing the results of expression
The spoken language can be very ambiguous. The term equals is one of those
ambiguities. The word equals can mean that two things have the same value
as in “5 cents equals a nickel.” Equals can also imply assignment, as in math
when you say that “y equals 3 times x.”
To avoid ambiguity, C++ programmers call the assignment operator, which says
(in effect), Store the results of the expression to the right of the equal sign in
the variable to the left. Programmers say that “factor is assigned the value
212 minus 32.”
Never say “factor is equal to 212 minus 32.” You’ll hear this from some lazy
types, but you and I know better.
Examining the remainder of
Conversion.cpp
The second expression in Conversion.cpp presents a slightly more compli
cated expression than the first. This expression uses the same mathematical
symbols: * for multiplication, / for division and, + for addition. In this case, how
ever, the calculation is performed on variables and not simply on constants.
The value contained in the variable called factor (calculated immediately
prior, by the way) is multiplied by the value contained in celsius (which was
input from the keyboard). The result is divided by 100 and summed with 32. The
result of the total expression is assigned to the integer variable fahrenheit.
The final two commands output the string Fahrenheit value is: to the
display, followed by the value of fahrenheit — and all so fast that the user
scarcely knows it’s going on.
Chapter 2
Declaring Variables Constantly
In This Chapter
Declaring variables
Declaring different types of variables
Using floating-point variables
Declaring and using other variable types
T he most fundamental of all concepts in C++ is the variable — a variable is
like a small box. You can store things in the box for later use, particularly
numbers. The concept of a variable is borrowed from mathematics. A state
ment such as
x = 1
stores the value 1 in the variable x. From that point forward, the mathemati
cian can use the variable x in place of the constant 1 — until she changes the
value of x to something else.
Variables work the same way in C++. You can make the assignment
x = 1;
From that point forward in the program, until the value of x is changed, any
references to x are the same as referencing 1. That is, the value of x is 1.
Unfortunately, C++ has a few more concerns about variables than the mathe
matician does. This chapter deals with the care and feeding of variables in C++.
Declaring Variables
C++ saves numeric values in small storage boxes known as variables. Mathe
maticians throw variables around with abandon. A mathematician might (for
example) write down something like the following:
28 Part I: Introduction to C++ Programming
(x + 2) = y / 2
x + 4 = y
solve for x and y
Any reader who’s had algebra realizes right off that the mathematician has
introduced the variables x and y. But C++ isn’t that smart (computers may be
fast, but they’re stupid).
You have to announce each variable to C++ before you can use it. You have to
say something soothing like this:
int x;
x = 10;
int y;
y = 5;
These lines of code declare that a variable x exists, that it is of type int, and
that a variable y of type int also exists. (The next section discusses vari
able types.) You can declare variables (almost) anywhere you want in your
program — as long as you declare the variable before you use it.
Declaring Different Types of Variables
If you’re on friendly terms with math (hey, aren’t we all?), you probably think
of a variable in mathematics as an amorphous box capable of holding what
ever you might choose to store in it. You might easily write something like the
following:
x = 1
x = 2.3
x = “this is a sentence”
x = Texas
Alas, C++ is not that flexible. (On the other hand, C++ can do things that people
can’t do, such as add a billion numbers or so in a second, so let’s not get too
uppity.) To C++, there are different types of variables just as there are different
types of storage bins. Some storage bins are so small that they can only handle
a single number. It takes a larger bin to handle a sentence. Of course, no bin is
large enough to hold Texas (maybe Rhode Island or Delaware).
You have to tell C++ what size bin you need before you can use a C++ variable.
In addition, different types of variables have different properties. So far, you
have only seen the int type of variable in this chapter:
Chapter 2: Declaring Variables Constantly 29
int x;
x = 1;
The variable type int is the C++ equivalent of an integer — a number that
has no fractional part. (Integers are also known as counting numbers or whole
numbers.)
Integers are great for most calculations. You can make it up through most (if
not all) of elementary school with integers. It isn’t until you reach age 11 or
so that they start mucking up the waters with fractions. The same is true in
C++: More than 90 percent of all variables in C++ are declared to be of type int.
Unfortunately, int variables don’t always work properly in a program. If (for
example) you worked through the temperature-conversion program in Chap
ter 1, the program has a potential problem — it can only handle integer tem
peratures — whole numbers that don’t have a fractional part. This limitation
of using only integers doesn’t affect daily use because it isn’t likely that some
one (other than a meteorologist) would get all excited about entering a frac
tional temperature (such as 10.5 degrees). The lurking problem is not at all
obvious: The conversion program lops off the fractional portion of tempera
tures that it calculates, and just keeps going without complaint. This can result
in a lapse of accuracy that can be serious — for example, you wouldn’t want
to come up a half mile short of the runway on your next airplane trip due to a
navigational round-off.
Reviewing the limitations
of integers in C++
The int variable type is the C++ version of an integer. int variables suffer the
same limitations as their counting-number integer equivalents in math do.
Integer round-off
Consider the problem of calculating the average of three numbers. Given three
int variables — nValue1, nValue2, and nValue3 — an equation for calculat
ing the average is
int nAverage; int nValue1; int nValue2; int nValue3;
nAverage =(nValue1 + nValue2 + nValue3) / 3;
Because all three values are integers, the sum is assumed to be an integer.
Given the values 1, 2, and 2, the sum is 5. Divide that by 3, and you get 123, or
1.666. Given that all three variables nValue1, nValue2, and nValue3 are inte
gers, the sum is also assumed to be an integer. The result of the division is also
an integer. The resulting value of nAverage is unreasonable but logical: 1.
30 Part I: Introduction to C++ Programming
Lopping off the fractional part of a number is called truncation, or rounding
off. For many applications, truncation isn’t a big deal. Some folks might con
sider its results reasonable (not mathematicians or bookies, of course), but
integer truncation can create math mayhem in computer programs. Consider
the following equivalent formulation:
int nAverage; int nValue1; int nValue2; int nValue3;
nAverage = nValue1/3 + nValue2/3 + nValue3/3;
Plugging in the same 1, 2, and 2 values, the resulting value of nAverage is (talk
about logical-but-unreasonable) 0. To see how this can occur, consider that
13 truncates to 0, 23 truncates to 0, and 23 truncates to 0. The sum of 0, 0, and
0 is zero. (Sort of like that old song: “Nothing from nothing leaves nothing, ya
gotta be something . . .”) You can see that integer truncation can be completely
unacceptable.
Limited range
A second problem with the int variable type is its limited range. A normal
int variable can store a maximum value of 2,147,483,647 and a minimum value
of –2,147,483,648 — roughly from positive 2 billion to negative 2 billion, for a
total range of about 4 billion.
Two billion is a very large number: plenty big enough for most uses. But it’s
not large enough for some applications — for example, computer technology.
In fact, your computer probably executes faster than 2 gigahertz, depending
upon how old your computer is. (Giga is the prefix meaning billion.) A single
strand of communications fiber — the kind that’s been strung from one end
of the country to the other — can handle way more than 2 billion bits per
second.
C++ offers a little help by allowing you declare an integer to be unsigned, mean
ing that it cannot be negative. An unsigned int value type can represent a
number from 0 to 4,294,967,295, should the need arise for some unimaginable
reason.
You can declare a variable simply unsigned. The int is implied.
Solving the truncation problem
The limitations of int variables can be unacceptable in some applications.
Fortunately, C++ understands decimal numbers. A decimal number can have
a nonzero fractional part. (Mathematicians also call those real numbers.)
Decimal numbers avoid many of the limitations of int type integers. Notice
that a decimal number “can have” a nonzero fractional part. In C++, the
number 1.0 is just as much a decimal number as 1.5. The equivalent integer is
written simply as 1. Decimals numbers can also be negative, like –2.3.
Chapter 2: Declaring Variables Constantly 31
When you declare variables in C++ that are decimal numbers, you identify them
as double precision floating-point values. (Yes, there is such a critter as a
“single precision floating-point variable,” but stick with me here.) The term
floating-point means the decimal point is allowed to float back and forth, iden
tifying as many “decimal places” as necessary to express the value. Floating-
point variables are declared in the same way as int variables:
double dValue1;
From this point forward, the variable dValue1 is declared to be a double. Once
declared, you cannot change the type of a variable. dValue1 is now a double
and will be a double for the remainder of its natural instructions. To see how
floating-point numbers fix the truncation problem inherent with integers, con
vert all the int variables to double. Here’s what you get:
double dValue;
dValue = 1.0/3.0 + 2.0/3.0 + 2.0/3.0;
is equivalent to
dValue = 0.333... + 0.666... + 0.666...;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -