书名:C++ Without Fear
A Beginner’s Guide That Makes You Feel Smart
作者:Brian Overland
阅读时间:2018/10/6-2018/10/20
书摘+书评:
An important rule of good programming style is that variables should usually be initialized, which means giving them a value as soon as you declare them.
C++ also stores floating-point constants in double precision unless you specify otherwise (for example, by using the notation 12.5F instead of 12.5).
Type double stands for “double-precision floating point.”
building is the process of compiling and linking a program.
To print output and advance to the next line, use the cout object and send a newline character (endl). For example:
cout << "Never fear, C++ is here!" << endl;
Variables that may store a fractional portion should have type double. This stands for “double-precision floating point.” The single-precision type (float) should be used only when storing large amounts of floating-point data on disk.
You can assign values between integer and floating-point variables, but if you assign a floating-point value to an integer, the compiler complains about loss of data.
int n = 5;
double x = n; // Ok: convert 5 to floating-pt
n = 3.7; // Warning: convert from double to int
n = 3.0;/* This also gets a warning, because the presence of a decimal point (.) causes a value to be stored in floating-point (double) format.*/
What if, instead of executing one statement in response to a condition, you want to do a series of things? The answer is you can use a compound statement (or block):
if (x == y) {
cout << "x and y are equal." << endl;
cout << "Isn't that nice?";
they_are_equal = true;
}
The significance of the block is that either all these statements are executed or none of them is executed. If the condition is not true, the program jumps past the end of the block. A block can be plugged into the if statement syntax because of another cardinal rule:
✱ Anywhere you can use a statement in C++ syntax, you can use a compound statement (or block).
The block itself is not terminated by a semicolon (;)—only the statements inside are terminated by a semicolon. This is one of the few exceptions to the general rule that statements end with a semicolon in C++.
C++ treats “x = y” as an expression that produces a value. And there’d be nothing wrong with that, except that almost any valid numeric expression can be used as a condition. Therefore, the compiler does not complain if you write this, even though it’s usually wrong:
if (x = y)
// Do action... (Probably should have used ==)
The following statement divides by 2 and gets the remainder. This is called modulus or remainder division. The result is stored in a variable named (appropriately enough) “remainder.”
int remainder = n % 2;
Dividing two integers pr