⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch03.htm

📁 C++ From Scratch: An Object-Oriented Approach is designed to walk novice programmers through the ana
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<pre><tt>if (  (x &gt; 5)  &amp;&amp; (y &gt; 5 ||  z &gt; 5) )</tt></pre><p>Using the values that were mentioned earlier, this statement is false. Because   it is not true that x is greater than <tt>5</tt>, the left side of the AND statement   fails, so the entire statement is false. Remember that an AND statement requires   that both sides be true: Something isn't both "good tasting" AND "good for you"   if it isn't good tasting.</p><blockquote>  <hr>  <p><strong>NOTE: </strong> It is often a good idea to use extra parentheses     to clarify what you want to group. Remember, the goal is to write programs     that work and that are easy to read and understand. It is easier to understand</p>  <p> <tt>(8 * 5) + 3</tt></p>  <p> than</p>  <p> <tt>8 * 5 + 3</tt></p>  <p> even though the result is the same. <a name="_Toc448989117"></a></p>  <hr></blockquote><h3> <a name="Heading10">Putting It All Together</a></h3><p>Following is the <tt>while</tt> statement you'll use to see whether you have   a reasonable number of letters:</p><pre><tt>while ( howManyLetters &lt; minLetters || howManyLetters &gt; maxLetters )</tt><tt>{</tt><tt>     //...</tt><tt>}</tt></pre><p>This reads "As long as the condition is true, do the work between the braces."   The condition that is tested is that either <tt>howManyLetters</tt> is less   than <tt>minLetters</tt> OR <tt>howManyLetters</tt> is greater than <tt>maxLetters</tt>.</p><p>Thus, if the user enters <tt>0</tt> or <tt>1</tt>, <tt>howManyLetters</tt>   is less than <tt>minLetters</tt>, the condition is true, and the body of the   <tt>while</tt> loop executes. <a name="_Toc441727832"></a><a name="_Toc448989118"></a></p><h3> <a name="Heading11">do while</a></h3><p>Because <tt>howManyLetters</tt> is initialized to zero, you know that this   <tt>while</tt> loop will run at least once. If you do not want to rely on the   initial value of <tt>howManyLetters</tt> but you want to ensure that the loop   runs at least once in any case, you can use a slight variant on the <tt>while</tt>   loop--the <tt>do while</tt> loop:</p><pre><tt>do statement</tt><tt>    while ( condition )</tt></pre><p>This says that you will do the body of the loop while the condition is true.   The loop must run at least once because the condition is not tested until after   the statement executes the first time. So you can rewrite your loop as follows:</p><pre><tt>do</tt><tt>{</tt><tt>     //...</tt><tt>} while ( howManyLetters &lt; minLetters || howManyLetters &gt; maxLetters )</tt></pre><p>You know you need a <tt>do while</tt> loop when you are staring at a <tt>while</tt>   loop and find your self saying, "Dang, I want this to run at least once!" <a name="_Toc441727834"></a></p><blockquote>  <hr>  <p> <tt><b>do while</b></tt>--A <tt>while</tt> loop that executes at least once     and continues to exit while the condition that is tested is true. <a name="_Toc448989119"></a></p>  <hr></blockquote><h3> <a name="Heading12">Enumerated Constants</a></h3><p>When I have constants that belong together, I can create <i>enumerated</i>   constants. An enumerated constant is not quite a <i>type</i>; it is more of   a collection of related constants. </p><p>The syntax for enumerated constants is to write the keyword <tt>enum</tt>,   followed by the enumeration name, an open brace, each of the legal values (separated   by commas), and a closing brace and a semicolon. Here's an example:</p><pre><tt>enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };</tt></pre><p>This statement performs two tasks:</p><p><dl>   <dt>  <dd>     <p><b>1.</b> It makes <tt>COLOR</tt> the name of an enumeration.</p>  <dt>  <dd>     <p><b>2.</b> It makes <tt>RED</tt> a symbolic constant with the value <tt>0</tt>,       <tt>BLUE</tt> a symbolic constant with the value <tt>1</tt>, <tt>GREEN</tt>       a symbolic constant with the value <tt>2</tt>, and so on.   </dl><p></p><p>Every enumerated constant has an integer value. If you don't specify otherwise,   the first constant has the value <tt>0</tt> and the rest count up from there.   Any one of the constants can be initialized with a particular value, however,   and those that are not initialized count upward from the ones before them. Thus,   if you write</p><pre><tt>enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };</tt></pre><p><tt>RED</tt> has the value <tt>100</tt>; <tt>BLUE</tt>, the value <tt>101</tt>;   <tt>GREEN</tt>, the value <tt>500</tt>; <tt>WHITE</tt>, the value <tt>501</tt>;   and <tt>BLACK</tt>, the value <tt>700</tt>.</p><p>In this case you'll create an <tt>enum</tt> called <tt>BoundedValues</tt> and   establish the values you need:</p><pre><tt>enum BoundedValues  </tt><tt>{ </tt><tt>minPos = 2, </tt><tt>maxPos = 10, </tt><tt>minLetters = 2, </tt><tt>maxLetters = 26 </tt><tt>};</tt></pre><p>This replaces the four constant integers described previously. Frankly, there   often is little advantage to enumerated constants, except that they keep these   values together in one place. If, on the other hand, you are creating a number   of constants and you don't particularly care what their value is so long as   they all have unique values, enumerated constants can be quite useful.</p><p>Enumerated constants are most often used for comparison or testing, which is   how you use them here. You'll test whether <tt>minLetters</tt> is greater or   less than these enumerated values.</p><h3> <a name="Heading13">Returning to the Code</a></h3><p>Let's look at the code beginning on line 37 and ending on line 49:</p><pre><tt>37:        while ( howManyLetters &lt; minLetters </tt><tt>38:           || howManyLetters &gt; maxLetters )</tt><tt>39:        {</tt><tt>40:           cout &lt;&lt; "How many letters? (";</tt><tt>41:           cout &lt;&lt; minLetters &lt;&lt; "-" &lt;&lt; maxLetters &lt;&lt; "): ";</tt><tt>42:           cin &gt;&gt; howManyLetters;</tt><tt>43:           if ( howManyLetters &lt; minLetters </tt><tt>44:              || howManyLetters &gt; maxLetters )</tt><tt>45:           {</tt><tt>46:              cout &lt;&lt; "please enter a number between "; </tt><tt>47:              cout &lt;&lt; minLetters &lt;&lt; " and " &lt;&lt; maxLetters &lt;&lt; endl;</tt><tt>48:           }</tt><tt>49:        }</tt></pre><p></p><p>The goal of this statement is to continue to prompt the user for an entry that   is greater than <tt>minLetters</tt> and smaller than <tt>maxLetters</tt>.</p><p>The purpose of the <tt>if</tt> statement is to issue a reminder message if   the number that is entered is out of bounds. Here's how the code reads in words:</p><pre><tt>37:        while ( howManyLetters &lt; minLetters</tt><tt>38:           || howManyLetters &gt; maxLetters )</tt></pre><p>While it is either true that the value <tt>howManyLetters</tt> is smaller than   <tt>minLetters</tt> or it is true that <tt>howManyLetters</tt> is greater than   <tt>maxLetters</tt>,</p><pre><tt>    cout &lt;&lt; "How many letters? (";</tt><tt>    cout &lt;&lt; minLetters &lt;&lt; "-" &lt;&lt; maxLetters &lt;&lt; "): ";</tt><tt>    cin &gt;&gt; howManyLetters;</tt></pre><p>prompts the user and captures the user's response in the variable <tt>howManyLetters</tt>:</p><pre><tt>    if ( howManyLetters &lt; minLetters </tt><tt>    || howManyLetters &gt; maxLetters )</tt></pre><p>Test the response; if it is either smaller than <tt>minLetters</tt> or greater   than <tt>maxLetters</tt>,</p><pre><tt>{</tt><tt>     cout &lt;&lt; "please enter a number between "; </tt><tt>     cout &lt;&lt; minLetters &lt;&lt; " and " &lt;&lt; maxLetters &lt;&lt; endl;</tt><tt>}</tt></pre><p>prints out the reminder message.</p><p>The logic of this next <tt>while</tt> loop, shown on line 51, is identical   to the preceding one. <a name="_Toc448989121"></a></p><h3> <a name="Heading14">Getting a Boolean Answer from the User</a></h3><p>It is now time to ask the user whether he or she wants to allow duplicates   (on line 72). You have a problem, however. The local variable <tt>duplicatesAllowed</tt>   is of type <tt>bool</tt>, which, you'll remember, is a type that evaluates either   to <tt>true</tt> or <tt>false</tt><i>. </i></p><p>You cannot capture a Boolean value from the user. The user can enter a number   (using <tt>cin</tt> to save it in an <tt>int</tt> variable) or a character (using   <tt>cin</tt> to save it in a character variable). There are some other choices   as well, but Boolean is not one of them.</p><p>Here's how you'll do it: You'll prompt the user to enter a letter, <i>y</i>   or <i>n</i>, and you'll then set the Boolean value based on what is entered.</p><p>The first task is to capture the response, and here you need something very   much like the <tt>while</tt> logic that was shown previously for the letters.   That is, you create a variable, as shown on line 65, initialize it to an invalid   answer (in this case, space), and then continue to prompt until the user gives   you an acceptable answer (<tt>'y'</tt> or <tt>'n'</tt>):</p><pre><tt>char choice = ' ';</tt><tt>while ( choice != 'y' &amp;&amp; choice != 'n' )</tt><tt>{</tt><tt>    cout &lt;&lt; "Allow duplicates (y/n)? ";</tt><tt>    cin &gt;&gt; choice;</tt><tt>}</tt></pre><p>Begin by defining and initializing a character variable, <tt>choice</tt>. You   can initialize it to a space by enclosing a space in single quotes, as described   in Chapter 2.</p><p>Once again, you use a <tt>while</tt> loop to test whether you have valid data.   This time, you will test to see whether <tt>choice</tt> is not equal to <tt>'y'</tt>   or <tt>'n'</tt>.</p><p>If it is true that <tt>choice</tt> is not equal to (<tt>!=</tt>) <tt>'y'</tt>,   and it is also true that <tt>choice</tt> is not equal to <tt>'n'</tt>, the expression   returns <tt>true</tt> and the <tt>while</tt> statement executes.</p><p>Your next task is to test the value in <tt>choice</tt> (which must now be <tt>'y'</tt>   or <tt>'n'</tt>) and set <tt>duplicatesAllowed</tt> accordingly. You can certainly   use an <tt>if</tt> statement:</p><pre><tt>if ( choice == 'y')</tt><tt>    duplicatesAllowed = true;</tt><tt>else</tt><tt>    duplicatesAllowed = false;<a name="_Toc448989122"></a><a name="_Toc441727709"></a></tt></pre><h3> <a name="Heading15">Equality Operator ==</a></h3><a name="WhereWasI"></a><p>The equality operator (<tt>==</tt>) tests whether two objects are the same.   With integers, two variables are equal if they have the same value (for example,   if x is assigned the value <tt>4</tt> and y is assigned the value <tt>2*2</tt>,   they are equal). With character variables, they are equal if they have the same   character value. No surprises here. We test for equality on line 72 to see if   <tt>choice</tt> is equal to the letter <tt>'y'</tt>. </p><blockquote>  <hr>  <p> <b>Equality operator (<tt>==</tt>)</b>--Determines whether two objects have     the same value. Be careful with this; you need two equal signs. A single equal     sign (=) indicates <i>assignment</i> in C++. Thus, if you write</p>  <p> a = b</p>  <p> in C++ you assign the value currently in b to the variable a. If you want     to test if they are equal, you must write</p>  <p> a == b <a name="_Toc448989123"></a></p>  <hr></blockquote><h3> <a name="Heading16"> else</a></h3><p>Often your program wants to take one branch if your condition is true, another   if it is false. The keyword <tt>else</tt> indicates what the compiler is to   execute if the tested expression evaluates <tt>false</tt>:</p><pre><tt>if (expression)</tt><tt>    statement;</tt><tt>else</tt><tt>    statement;</tt></pre><blockquote>  <hr>  <p> <tt><b>else</b></tt>--An <tt>else</tt> statement is executed only when an     <tt>if</tt> statement evaluates to <tt>false</tt>.</p>  <hr></blockquote><p>Thus, the code shown says, "If <tt>choice</tt> is equal to <tt>y</tt>, set   <tt>duplicatesAllowed</tt> to <tt>true</tt>; otherwise (<tt>else</tt>), set   it to <tt>false</tt>." <a name="_Toc448989124"></a></p><h3> <a name="Heading17">The Conditional (or ternary) Operator</a></h3><p>You're trying to assign the value <tt>duplicatesAllowed</tt> depending on the   value of <tt>choice</tt>. In English you might want to say, "Is <tt>choice</tt>   equal to <tt>y</tt>? If so, set <tt>duplicatesAllowed</tt> equal to <tt>true</tt>;   otherwise, set it to <tt>false</tt>."</p><p>C++ has an operator that does exactly what you want.</p><p>The conditional operator (<tt>?:</tt>) is C++'s only ternary operator: It is   the only operator to take three terms.</p><blockquote>  <hr>  <p><strong>NOTE: </strong> The <i>arity</i> of an operator describes how many     terms are used. For example, a <i>binary</i> operator, such as the addition     operator (<tt>+</tt>), uses two terms: <tt>a+b</tt>. In this case, <tt>a</tt>     and <tt>b</tt> are the two terms.</p>  <p> C++ has a few <i>unary</i> operators, but you've not seen them yet. The     conditional operator is C++'s only ternary operator, and thus the terms <i>conditional</i>     operator and <i>ternary</i> operator are often used interchangeably.</p>  <hr></blockquote><blockquote>  <hr>  <p> <b>arity</b>--How many terms an operator uses</p>  <p> <b>unary</b>--An operator that uses only one term</p>  <p> <b>binary</b>--An operator that uses two terms</p>  <p> <b>ternary</b>--An operator that uses three terms</p>  <hr></blockquote><p>The conditional operator takes three terms and returns a value. In fact, all   three terms are expressions; that is, they can be statements that return a value:</p><pre><tt>(expression1) ? (expression2) : (expression3)</tt></pre><p>This line is read as follows: "If <tt>expression1</tt> is true, return the   value of <tt>expression2</tt>; otherwise, return the value of <tt>expression3</tt>."   Typically, this value is assigned to a variable.</p><p>Thus, line 72 shows</p><pre><tt>duplicatesAllowed = (choice == y) ? true : false;</tt></pre><p>Figure 3.1 illustrates each of the operators and terms.</p><p><b>Figure 3.1 </b><i>Dissecting a statement.</i></p><p>This line is read as follows: "Is it true that <tt>choice</tt> equals the character   <tt>'y'</tt>? If so, assign <tt>true</tt> to <tt>duplicatesAllowed</tt>; otherwise,   assign <tt>false</tt>."</p><p>After you are comfortable with the conditional operator, it is clean, quick,   and easy to use. <a name="_Toc448989125"></a></p><h3> <a name="Heading18">Putting It All Together</a></h3><p>You are now ready to analyze the <tt>while</tt> loop, beginning at line 35.   You start at line 27 by establishing <tt>valid</tt> as a Boolean operator that   is initialized to <tt>false</tt>. </p><pre><tt>while ( ! valid )</tt></pre><p>The <tt>while</tt> loop executes while <tt>valid</tt> is false. Because <tt>valid</tt>   was initialized to <tt>false</tt>, the <tt>while</tt> loop will certainly execute   the first time through. This <tt>while</tt> loop begins with the opening brace   on line 36 and ends at the closing brace on line 86.</p><p>This entire loop continues to execute until and unless <tt>valid</tt> is set   to <tt>true</tt>.</p><p>Within this <tt>while</tt> loop are a series of interior <tt>while</tt> loops   that solicit and test the values for <tt>howManyLetters</tt>, <tt>howManyPositions</tt>,   and, ultimately (if indirectly), <tt>duplicatesAllowed</tt>:</p><pre><tt> ( ! duplicatesAllowed &amp;&amp; howManyPositions &gt; howManyLetters )</tt></pre><p>Finally, after the values are gathered, on line 74 you test the logic of the   choices. If it is true that duplicates are not allowed, and it is also true   that <tt>howManyPositions</tt> (provided by the user) is greater than the number   the user chose for <tt>howManyLetters</tt>, you have a problem: You need to   put five letters in six positions without duplicating any letters--it can't   be done. </p><p>In this case, you execute the <tt>if</tt> statement and write to the screen,   "I can't put five letters in six positions without duplicates! Please try again."   You then reinitialize <tt>howManyLetters</tt> and <tt>howManyPositions</tt>   to zero. Make sure that you understand why. Hint: check the <tt>while</tt> loops   in which these variables are assigned the user's choice.</p><p>If, on the other hand, the <tt>if</tt> statement fails (if duplicates are allowed   or if <tt>howManyPositions</tt> is not greater than <tt>howManyLetters)</tt>,   the <tt>else</tt> statement executes, <tt>valid</tt> is set to <tt>true</tt>,   and the <tt>while</tt> loop terminates.</p><h2> </h2><CENTER><P><HR>  <A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A> <BR>  <BR><p></P><P>&#169; <A HREF="../copy.htm">Copyright 1999</A>, Macmillan Computer Publishing. Allrights reserved.</p></CENTER></BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -