📄 chapter02.html
字号:
<P>Rather than memorize the list, I would suggest that you take advantage of afeature provided in many development environments: code highlighting. As youtype, different parts of your program should appear in different colors. Forexample, keywords might be blue, strings red, and other code black. If you type a variable name and it turns blue, watch out! You might get some strangebehavior from the compiler.</P><BR><BR><H3>2.7 Operators</H3><B>Operators</B> are special symbols that are used to represent simple computations like addition and multiplication. Most of the operators in C++ do exactly what you would expect them to do, because they are common mathematical symbols. For example, the operator for adding two integers is <TT>+</TT>.</P><P>The following are all legal C++ expressions whose meaning is more or less obvious:</P><PRE>1+1 hour-1 hour*60 + minute minute/60</PRE><P>Expressions can contain both variables names and integer values. In each case the name of the variable is replaced with its value before the computationis performed.</P><P>Addition, subtraction and multiplication all do what you expect, but youmight be surprised by division. For example, the following program:</P><PRE> int hour, minute; hour = 11; minute = 59; cout << "Number of minutes since midnight: "; cout << hour*60 + minute << endl; cout << "Fraction of the hour that has passed: "; cout << minute/60 << endl;</PRE><P>would generate the following output:</P><PRE>Number of minutes since midnight: 719Fraction of the hour that has passed: 0</PRE><P>The first line is what we expected, but the second line is odd. The valueof the variable <TT>minute</TT> is 59, and 59 divided by 60 is 0.98333, not 0.The reason for the discrepancy is that C++ is performing <B>integer division</B>.</P><P>When both of the <B>operands</B> are integers (operands are the thingsoperators operate on), the result must also be an integer, and by definitioninteger division always rounds <I>down</I>, even in cases like this where thenext integer is so close.</P><P>A possible alternative in this case is to calculate a percentage rather thana fraction:</P><PRE> cout << "Percentage of the hour that has passed: "; cout << minute*100/60 << endl;</PRE><P>The result is:</P><PRE>Percentage of the hour that has passed: 98</PRE><P>Again the result is rounded down, but at least now the answer is approximately correct. In order to get an even more accurate answer, we could use a different type of variable, called floating-point, that is capable of storing fractional values. We'll get to that in the next chapter.</P><BR><BR><H3>2.8 Order of operations</H3><P>When more than one operator appears in an expression the order of evaluationdepends on the rules of <B>precedence</B>. A complete explanation of precedence can get complicated, but just to get you started:</P><OL> <LI>Multiplication and division happen before addition and subtraction. So <TT>2*3-1</TT> yields 5, not 4, and <TT>2/3-1</TT> yields -1, not 1 (remember that in integer division <TT>2/3</TT> is 0).</LI> <LI>If the operators have the same precedence they are evaluated from left to right. So in the expression <TT>minute*100/60</TT>, the multiplication happens first, yielding <TT>5900/60</TT>, which in turn yields <TT>98</TT>. If the operations had gone from right to left, the result would be <TT>59*1</TT> which is <TT>59</TT>, which is wrong.</LI> <LI>Any time you want to override the rules of precedence (or you are not sure what they are) you can use parentheses. Expressions in parentheses are evaluated first, so <TT>2 * (3-1)</TT> is 4. You can also use parentheses to make an expression easier to read, as in <TT>(minute * 100) / 60</TT>, even though it doesn't change the result.</LI></OL><BR><BR><H3>2.9 Operators for characters</H3><P>Interestingly, the same mathematical operations that work on integers alsowork on characters. For example,</P><PRE> char letter; letter = 'a' + 1; cout << letter << endl;</PRE><P>outputs the letter <TT>b</TT>. Although it is syntactically legal to multiply characters, it is almost never useful to do it. Earlier I said that you can only assign integer values to integer variables and character values to character variables, but that is not completely true. In some cases, C++ converts automatically between types. For example, the following is legal.</P><PRE> int number; number = 'a'; cout << number << endl;</PRE><P>The result is 97, which is the number that is used internally by C++ to represent the letter <TT>'a'</TT>. However, it is generally a good idea to treat characters as characters, and integers as integers, and only convert from one to the other if there is a good reason.</P><P>Automatic type conversion is an example of a common problem in designing aprogramming language, which is that there is a conflict between <B>formalism</B>, which is the requirement that formal languages should havesimple rules with few exceptions, and <B>convenience</B>, which is the requirement that programming languages be easy to use in practice.</P><P>More often than not, convenience wins, which is usually good for expert programmers, who are spared from rigorous but unwieldy formalism, but bad for beginning programmers, who are often baffled by the complexity of the rules andthe number of exceptions. In this book I have tried to simplify things by emphasizing the rules and omitting many of the exceptions.</P><BR><BR><H3>2.10 Composition</H3><P>So far we have looked at the elements of a programming language---variables,expressions, and statements---in isolation, without talking about how to combine them.</P><P>One of the most useful features of programming languages is their ability totake small building blocks and <B>compose</B> them. For example, we know how to multiply integers and we know how to output values; it turns out we can do both at the same time:</P><PRE> cout << 17 * 3;</PRE><P>Actually, I shouldn't say ``at the same time,'' since in reality the multiplication has to happen before the output, but the point is that any expression, involving numbers, characters, and variables, can be used inside an output statement. We've already seen one example:</P><PRE> cout << hour*60 + minute << endl;</PRE><P>You can also put arbitrary expressions on the right-hand side of an assignment statement:</P><PRE> int percentage; percentage = (minute * 100) / 60;</PRE><P>This ability may not seem so impressive now, but we will see other examples where composition makes it possible to express complex computations neatly and concisely.</P><P>WARNING: There are limits on where you can use certain expressions; most notably, the left-hand side of an assignment statement has to be a <I>variable</I> name, not an expression. That's because the left side indicates the storage location where the result will go. Expressions do not represent storage locations, only values. So the following is illegal: <TT>minute+1 = hour;</TT>.</P><BR><BR><H3>2.11 Glossary</H3><DL> <DT>variable:</DT><DD>A named storage location for values. All variables have a type, which determines which values it can store.</DD> <DT>value:</DT><DD>A letter, or number, or other thing that can be stored in a variable.</DD> <DT>type:</DT><DD>A set of values. The types we have seen are integers (<TT>int</TT> in C++) and characters (<TT>char</TT> in C++).</DD> <DT>keyword:</DT><DD> A reserved word that is used by the compiler to parse programs. Examples we have seen include <TT>int</TT>, <TT>void</TT> and <TT>endl</TT>. <DT>statement:</DT><DD>A line of code that represents a command or action. So far, the statements we have seen are declarations, assignments, and output statements.</DD> <DT>declaration:</DT><DD>A statement that creates a new variable and determines its type.</DD> <DT>assignment:</DT><DD>A statement that assigns a value to a variable.</DD> <DT>expression:</DT><DD>A combination of variables, operators and values that represents a single result value. Expressions also have types, as determined by their operators and operands.</DD> <DT>operator:</DT><DD>A special symbol that represents a simple computation like addition or multiplication.</DD> <DT>operand:</DT><DD>One of the values on which an operator operates.</DD> <DT>precedence:</DT><DD>The order in which operations are evaluated.</DD> <DT>composition:</DT><DD>The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.</DD></DL><BR><DIV CLASS=navigation><HR> <TABLE ALIGN=center WIDTH="100%" CELLPADDING=0 CELLSPACING=2> <TR> <TD><A HREF="chapter03.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter03.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="next" SRC="images/next.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/next.gif"></A> </TD> <TD><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="up" SRC="images/up.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/up.gif"></A> </TD> <TD><A HREF="chapter01.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter01.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="previous" SRC="images/previous.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/previous.gif"></A> </TD> <TD ALIGN=center BGCOLOR="#99CCFF" WIDTH="100%"> <B CLASS=title>How to Think Like a Computer Scientist: Chapter 2</B> </TD> <TD><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="contents" SRC="images/contents.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/contents.gif"></A> </TD> <TD> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="" SRC="images/blank.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/blank.gif"> </TD> <TD> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="" SRC="images/blank.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/blank.gif"> </TD> </TR> </TABLE> <B CLASS=navlabel>Next:</B> <SPAN CLASS=sectref><A HREF="chapter03.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter03.html">Chapter 3</A></SPAN> <B CLASS=navlabel>Up:</B> <SPAN CLASS=sectref><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html">Index</A></SPAN> <B CLASS=navlabel>Previous:</B> <SPAN CLASS=sectref><A HREF="chapter01.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter01.html">Chapter 1</A></SPAN> <HR></DIV></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -