📄 chapter04.html
字号:
<HTML><HEAD> <TITLE>Chapter 4</TITLE> <LINK REL="STYLESHEET" HREF="downey.css" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/downey.css"></HEAD><BODY><H2>Chapter 4</H2><H1>Conditionals and recursion</H1><H3>4.1 The modulus operator</H3><P>The modulus operator works on integers (and integer expressions) and yields the <I>remainder</I> when the first operand is divided by the second. In C++, the modulus operator is a percent sign, <TT>%</TT>. The syntax is exactly the same as for other operators:</P><PRE> int quotient = 7 / 3; int remainder = 7 % 3;</PRE><P>The first operator, integer division, yields 2. The second operator yields 1. Thus, 7 divided by 3 is 2 with 1 left over.</P>The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if <TT>x % y</TT> is zero, then <TT>x</TT> is divisible by <TT>y</TT>.</P><P>Also, you can use the modulus operator to extract the rightmost digit or digits from a number. For example, <TT>x % 10</TT> yields the rightmost digit of <TT>x</TT> (in base 10). Similarly <TT>x % 100</TT> yields the last two digits.</P><BR><BR><H3>4.2 Conditional execution</H3><P>In order to write useful programs, we almost always need the ability to check certain conditions and change the behavior of the program accordingly. <B>Conditional statements</B> give us this ability. The simplest form is the <TT>if</TT> statement:</P><PRE> if (x > 0) { cout << "x is positive" << endl; }</PRE><P>The expression in parentheses is called the condition. If it is true, then the statements in brackets get executed. If the condition is not true, nothinghappens.</P><P>The condition can contain any of the <TT>comparison operators</TT>:</P><PRE> x == y // x equals y x != y // x is not equal to y x > y // x is greater than y x < y // x is less than y x >= y // x is greater than or equal to y x <= y // x is less than or equal to y</PRE><P>Although these operations are probably familiar to you, the syntax C++ uses is a little different from symbols used in mathematics. A common error is to use a single <TT>=</TT> instead of a double <TT>==</TT>. Remember that <TT>=</TT> is the assignment operator, and <TT>==</TT> is a comparison operator. Also, there is no such thing as <TT>=<</TT> or <TT>=></TT>.</P><P>The two sides of a condition operator have to be the same type. You can only compare <TT>ints</TT> to <TT>ints</TT> and <TT>doubles</TT> to <TT>doubles</TT>. Unfortunately, at this point you can't compare <TT>String</TT>s at all! There is a way to compare <TT>String</TT>s, but we won't get to it for a couple of chapters.</P><BR><BR><H3>4.3 Alternative execution</H3>A second form of conditional execution is alternative execution,in which there are two possibilities, and the condition determineswhich one gets executed. The syntax looks like:<PRE> if (x%2 == 0) { cout << "x is even" << endl; } else { cout << "x is odd" << endl; }</PRE><P>If the remainder when <TT>x</TT> is divided by 2 is zero, then we know that <TT>x</TT> is even, and this code displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will beexecuted.</P><P>As an aside, if you think you might want to check the parity (evenness or oddness) of numbers often, you might want to ``wrap'' this code up in a function, as follows:</P><PRE>void printParity (int x) { if (x%2 == 0) { cout << "x is even" << endl; } else { cout << "x is odd" << endl; }}</PRE><P>Now you have a function named <TT>printParity</TT> that will display an appropriate message for any integer you care to provide. In <TT>main</TT> you would call this function as follows:</P><PRE> printParity (17);</PRE><P>Always remember that when you <I>call</I> a function, you do not have to declare the types of the arguments you provide. C++ can figure out what type they are. You should resist the temptation to write things like:</P><PRE> int number = 17; printParity (int number); // WRONG!!!</PRE><BR><BR><H3>4.4 Chained conditionals</H3><P>Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by <B>chaining</B> a series of <TT>if</TT>s and <TT>else</TT>s:</P><PRE> if (x > 0) { cout << "x is positive" << endl; } else if (x < 0) { cout << "x is negative" << endl; } else { cout << "x is zero" << endl; }</PRE><P>These chains can be as long as you want, although they can be difficult to read if they get out of hand. One way to make them easier to read is to use standard indentation, as demonstrated in these examples. If you keep all thestatements and squiggly-braces lined up, you are less likely to make syntax errors and you can find them more quickly if you do.</P><BR><BR><H3>4.5 Nested conditionals</H3><P>In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:</P><PRE> if (x == 0) { cout << "x is zero" << endl; } else { if (x > 0) { cout << "x is positive" << endl; } else { cout << "x is negative" << endl; } }</PRE><P>There is now an outer conditional that contains two branches. The first branch contains a simple output statement, but the second branch contains another <TT>if</TT> statement, which has two branches of its own. Fortunately,those two branches are both output statements, although they could have been conditional statements as well.</P><P>Notice again that indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. In general, it is a good idea to avoid them when you can.</P>On the other hand, this kind of <B>nested structure</B> is common, and we will see it again, so you better get used to it.</P><BR><BR><H3>4.6 The <TT>return</TT> statement</H3><P>The <TT>return</TT> statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if you detect an error condition:</P><PRE>#include <math.h>void printLogarithm (double x) { if (x <= 0.0) { cout << "Positive numbers only, please." << endl; return; } double result = log (x); cout << "The log of x is " << result);}</PRE><P>This defines a function named <TT>printLogarithm</TT> that takes a <TT>double</TT> named <TT>x</TT> as a parameter. The first thing it does is check whether <TT>x</TT> is less than or equal to zero, in which case it displays an error message and then uses <TT>return</TT> to exit the function. The flow of execution immediately returns to the caller and the remaining linesof the function are not executed.</P><P>I used a floating-point value on the right side of the condition because there is a floating-point variable on the left.</P><P>Remember that any time you want to use one a function from the math library,you have to include the header file <TT>math.h</TT>.</P><BR><BR><H3>4.7 Recursion</H3><P>I mentioned in the last chapter that it is legal for one function to call another, and we have seen several examples of that. I neglected to mention that it is also legal for a function to call itself. It may not be obvious
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -