📄 c++ for dummys.txt
字号:
which results in the value
dValue = 1.666...;
I have written the value 1.6666 . . . as if the number of trailing 6s goes on
forever. This is (not necessarily) the case. There’s a limit to the number of digits
of accuracy of a double variable — but it’s a lot more than I can keep track of.
The programs IntAverage and FloatAverage are available on the enclosed
CD in the CPP_Programs\Chap02 directory to demonstrate this averaging
example.
Looking at the limits of
floating-point numbers
Although floating-point variables can solve many calculation problems such
as truncation, they have some limitations themselves — in effect, the reverse
of those associated with integer variables. double variables can’t be used as
counting numbers, they’re more difficult for the computer to handle, and they
also suffer from round-off error (though not nearly to the same degree as int
variables).
32 Part I: Introduction to C++ Programming
Counting
You cannot use floating-point variables in applications where counting is impor
tant. This includes C++ constructs, which requires counting ability. C++ can’t
verify which whole number value is meant by a given floating-point number.
For example, it’s clear that 1.0 is 1. But what about 0.9 or 1.1? Should these also
be considered as 1? C++ simply avoids the problem by insisting on using int
values when counting is involved.
Calculation speed
Historically, a computer processor can process integer arithmetic quicker than
it can floating-point arithmetic. Thus, while a processor can add 1 million inte
ger numbers in a given amount of time, the same processor may be able to
perform only 200,000 floating-point calculations during the same period. (Not
surprisingly, I couldn’t even get around to reading the first value.)
Calculation speed is becoming less of a problem as microprocessors increase
their capabilities. Most modern processors contain special calculation cir
cuitry for performing floating-point calculations almost as fast as integer
calculations.
Loss of accuracy
Floating-point variables cannot solve all computational problems. Floating-
point variables have a limited precision of about 6 digits — an extra-economy
size, double-strength version of float can handle some 15 significant digits with
room left over for lunch.
To evaluate the problem, consider that 13 is expressed as 0.333 . . . in a con
tinuing sequence. The concept of an infinite series makes sense in math, but
not to a computer. The computer has a finite accuracy. Average 1, 2, and 2
(for example), and you get 1.666667.
C++ can correct for many forms of round-off error. For example, in output, C++
can determine that instead of 0.999999, that the user really meant 1. In other
cases, even C++ cannot correct for round-off error.
Not-so-limited range
Although the double data type has a range much larger than that of an inte
ger, it’s still limited. The maximum value for an int is a skosh more than 2 bil
lion. The maximum value of a double variable is roughly 10 to the 38th power.
That’s 1 followed by 38 zeroes; it eats 2 billion for breakfast. (It’s even more
than the national debt, at least at the time of this writing.)
Only the first 13 digits or so have any meaning; the remaining 25 digits suffer
from floating-point round-off error.
Chapter 2: Declaring Variables Constantly 33
Declaring Variable Types
So far this chapter has been trumpeting that variables must be declared and
that they must be assigned a type. Fortunately (ta-dah!), C++ provides a num
ber of different variable types. See Table 2-1 for a list of variables, their advan
tages, and limitations.
Table 2-1 C++ Variables
Variable Example Purpose
int 1 A simple counting number, either positive or
negative.
unsigned int 1U A counting number that’s only non-negative.
long 10L A potentially larger version of int. There is
no difference between long and int with
Dev-C++ and Microsoft Visual C++.NET.
unsigned long 10UL A nonnegative long integer.
float 1.0F A single precision real number. This smaller
version takes less memory than a double
but has less accuracy and a smaller range.
double 1.0 A standard floating-point variable.
char ‘c’ A single char variable stores a single alpha
betic or digital character. Not suitable for
arithmetic.
string “this is A string of characters forms a sentence or
a string” phrase.
bool true The only other value is false. No I mean, it’s
really false. Logically false. Not “false” as
in fake or ersatz or . . . never mind.
It may seem odd that the standard floating length variable is called double
while the “off size” is float. In days gone by, memory was an expensive asset —
you could reap significant space savings by using a float variable. This is no
longer the case. That, combined with the fact that modern processors perform
double precision calculations at the same speed as float, makes the double
the default. Bigger is better, after all.
34 Part I: Introduction to C++ Programming
The following statement declares a variable lVariable as type long and sets
it equal to the value 1, while dVariable is a double set to the value 1.0:
// declare a variable and set it to 1
long lVariable;
lVariable = 1;
// declare a variable of type double and set it to 1.0
double dVariable;
dVariable = 1.0;
You can declare a variable and initialize it in the same statement:
int nVariable = 1; // declare a variable and
// initialize it to 1
Although such declarations are common, the only benefit to initializing a vari
able in the declaration is that it saves typing.
A char variable can hold a single character; a string (which isn’t really a vari
able but works like one for most purposes) holds a string of characters. Thus,
‘C’ is a char that contains the character C, whereas “C” is a string with one
character in it. A rough analogy is that a ‘C’ corresponds to a nail in your hand,
whereas “C” corresponds to a nail gun with one nail left in the magazine. (Chap
ter 9 describes strings in detail.)
If an application requires a string, you’ve gotta provide one, even if the string
contains only a single character. Providing nothing but the character just
won’t do the job.
Types of constants
A constant is an explicit number or character (such as 1, 0.5, or ‘c’) that doesn’t
change. As with variables, every constant has a type. In an expression such as
n = 1; (for example), the constant 1 is an int. To make 1 a long integer,
write the statement as n = 1L;. The analogy is as follows: 1 represents a single
ball in the bed of a pickup truck, whereas 1L is a single ball in the bed of a
dump truck. The ball is the same, but the capacity of its container is much
larger.
Following the int to long comparison, 1.0 represents the value 1, but in a
floating-point container. Notice, however, that the default for floating-point
constants is double. Thus, 1.0 is a double number and not a float.
true is a constant of type bool. However, “true” (note the quotation marks)
is a string of characters that spell out the word true. In addition, in keeping
with C++’s attention to case, true is a constant, but TRUE has no meaning.
Chapter 2: Declaring Variables Constantly 35
Special characters
You can store any printable character you want in a char or string vari
able. You can also store a set of non-printable characters that is used as
character constants. See Table 2-2 for a description of these important non-
printable characters.
Table 2-2 Special Characters
Character Constant Action
‘\n’ newline
‘\t’ tab
‘\0’ null
‘\\’ backslash
You have already seen the newline character at the end of strings. This char
acter breaks a string and puts the parts on separate lines. A newline charac
ter may appear anywhere within a string. For example,
“This is line 1\nThis is line 2”
appears on the output as
This is line 1
This is line 2
Similarly, the \t tab character moves output to the next tab position. (This
position can vary, depending on the type of computer you’re using to run the
program.) Because the backslash character is used to signify special charac
ters, a character pair for the backslash itself is required. The character pair
\\ represents the backslash.
C++ collision with file names
Windows uses the backslash character to sep Unfortunately, MS-DOS’s use of backslash con
arate folder names in the path to a file. (This is flicts with the use of backslash to indicate an
a remnant of MS-DOS that Windows has not escape character in C++. The character \\ is a
been able to shake.) Thus, Root\FolderA\ backslash in C++. The MS-DOS path Root\
Filerepresents Filewithin FolderA, which FolderA\Fileis represented in C++ string as
is a subdirectory of Root. Root\\FolderA\\File.
36 Part I: Introduction to C++ Programming
Are These Calculations Really Logical?
C++ provides a logical variable called bool. The type bool comes from Boolean,
the last name of the inventor of the logical calculus. There are two values for a
boolean variable: true and false.
There are actually calculations that result in the value bool. For example, “x
is equal to y” is either true or false.
Mixed Mode Expressions
C++ allows you to mix variable types in a single expression. That is, you are
allowed to add an integer with a double precision floating-point value. In the
following expression, for example, nValue1 is allowed to be an int:
// in the following expression the value of nValue1
// is converted into a double before performing the
// assignment
int nValue1 = 1;
nValue1 + 1.0;
An expression in which the two operands are not the same type is called a
mixed-mode expression. Mixed-mode expressions generate a value whose type
is equal to the more capable of the two operands. In this case, nValue1 is con
verted to a double before the calculation proceeds. Similarly, an expression of
one type may be assigned to a variable of a different type, as in the following
statement:
// in the following assignment, the whole
// number part of fVariable is stored into nVariable
double dVariable = 1.0;
int nVariable;
nVariable = dVariable;
You can lose precision or range if the variable on the left side of the assignment
is smaller. In the previous example, C++ truncates the value of dVariable
before storing it in nVariable.
Converting a larger value type into a smaller value type is c
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -