📄 ch04.htm
字号:
a value: <TT>1</TT> (<TT>TRUE</TT>) or <TT>0</TT> (<TT>FALSE</TT>). Like all expressions,they have a precedence order (see Appendix A) that determines which relations areevaluated first. This fact is important when determining the value of the statement</P><PRE><FONT COLOR="#0066FF">if ( x > 5 && y > 5 || z > 5)</FONT></PRE><P>It might be that the programmer wanted this expression to evaluate <TT>TRUE</TT>if both <TT>x</TT> and <TT>y</TT> are greater than 5 or if <TT>z</TT> is greaterthan 5. On the other hand, the programmer might have wanted this expression to evaluate<TT>TRUE</TT> only if <TT>x</TT> is greater than 5 and if it is also true that either<TT>y</TT> is greater than 5 or <TT>z</TT> is greater than 5.</P><P>If <TT>x</TT> is 3, and <TT>y</TT> and <TT>z</TT> are both 10, the first interpretationwill be true (<TT>z</TT> is greater than 5, so ignore <TT>x</TT> and <TT>y</TT>),but the second will be false (it isn't true that both <TT>x</TT> and <TT>y</TT> aregreater than 5 nor is it true that <TT>z</TT> is greater than 5).</P><P>Although precedence will determine which relation is evaluated first, parenthesescan both change the order and make the statement clearer:</P><PRE><FONT COLOR="#0066FF">if ( (x > 5) && (y > 5 || z > 5) )</FONT></PRE><P>Using the values from earlier, this statement is false. Because it is not truethat <TT>x</TT> is greater than 5, the left side of the <TT>AND</TT> statement fails,and thus the entire statement is false. Remember that an <TT>AND</TT> statement requiresthat both sides be true--something isn't both "good tasting" AND "goodfor you" if it isn't good tasting.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>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. <HR></BLOCKQUOTE><CENTER><H3><A NAME="Heading45"></A><FONT COLOR="#000077">More About Truth and Falsehood</FONT></H3></CENTER><P>In C++, zero is false, and any other value is true. Because an expression alwayshas a value, many C++ programmers take advantage of this feature in their <TT>if</TT>statements. A statement such as</P><PRE><FONT COLOR="#0066FF">if (x) // if x is true (nonzero) x = 0;</FONT></PRE><P>can be read as "If <TT>x</TT> has a nonzero value, set it to 0." Thisis a bit of a cheat; it would be clearer if written</P><PRE><FONT COLOR="#0066FF">if (x != 0) // if x is nonzero x = 0;</FONT></PRE><P>Both statements are legal, but the latter is clearer. It is good programming practiceto reserve the former method for true tests of logic, rather than for testing fornonzero values.</P><P>These two statements also are equivalent:</P><PRE><FONT COLOR="#0066FF">if (!x) // if x is false (zero)if (x == 0) // if x is zero</FONT></PRE><P>The second statement, however, is somewhat easier to understand and is more explicit.<BLOCKQUOTE> <P><HR><B>DO</B> put parentheses around your logical tests to make them clearer and to make the precedence explicit. <B>DO</B> use braces in nested <TT>if</TT> statements to make the <TT>else</TT> statements clearer and to avoid bugs. <B>DON'T</B> use <TT>if(x)</TT> as a synonym for <TT>if(x != 0)</TT>; the latter is clearer. <B>DON'T</B> use <TT>if(!x)</TT> as a synonym for <TT>if(x == 0)</TT>; the latter is clearer. <HR></P> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>It is common to define your own enumerated Boolean (logical) type with <TT>enum Bool {FALSE, TRUE};</TT>. This serves to set <TT>FALSE</TT> to <TT>0</TT> and <TT>TRUE</TT> to <TT>1</TT>. <HR></BLOCKQUOTE><CENTER><H3><A NAME="Heading46"></A><FONT COLOR="#000077">Conditional (Ternary) Operator</FONT></H3></CENTER><P>The conditional operator (<TT>?:</TT>) is C++'s only ternary operator; that is,it is the only operator to take three terms.</P><P>The conditional operator takes three expressions and returns a value:</P><PRE><FONT COLOR="#0066FF">(expression1) ? (expression2) : (expression3)</FONT></PRE><P>This line is read as "If expression1 is true, return the value of expression2;otherwise, return the value of expression3." Typically, this value would beassigned to a variable.</P><P>Listing 4.9 shows an <TT>if</TT> statement rewritten using the conditional operator.</P><P><A NAME="Heading47"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 4.9. A demonstrationof the conditional operator</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 4.9 - demonstrates the conditional operator2: //3: #include <iostream.h>4: int main()5: {6: int x, y, z;7: cout << "Enter two numbers.\n";8: cout << "First: ";9: cin >> x;10: cout << "\nSecond: ";11: cin >> y;12: cout << "\n";13:14: if (x > y)15: z = x;16: else17: z = y;18:19: cout << "z: " << z;20: cout << "\n";21:22: z = (x > y) ? x : y;23:24: cout << "z: " << z;25: cout << "\n";26: return 0;<TT>27: }</TT>Output: Enter two numbers.First: 5Second: 8z: 8z: 8</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis: </B></FONT>Three integer variables are created:<TT>x</TT>, <TT>y</TT>, and <TT>z</TT>. The first two are given values by the user.The <TT>if</TT> statement on line 14 tests to see which is larger and assigns thelarger value to <TT>z</TT>. This value is printed on line 19.<BR>The conditional operator on line 22 makes the same test and assigns <TT>z</TT> thelarger value. It is read like this: "If <TT>x</TT> is greater than <TT>y</TT>,return the value of <TT>x</TT>; otherwise, return the value of <TT>y</TT>."The value returned is assigned to <TT>z</TT>. That value is printed on line 24. Asyou can see, the conditional statement is a shorter equivalent to the <TT>if...else</TT>statement.<CENTER><H3><A NAME="Heading49"></A><FONT COLOR="#000077">Summary</FONT></H3></CENTER><P>This chapter has covered a lot of material. You have learned what C++ statementsand expressions are, what C++ operators do, and how C++ <TT>if</TT> statements work.</P><P>You have seen that a block of statements enclosed by a pair of braces can be usedanywhere a single statement can be used.</P><P>You have learned that every expression evaluates to a value, and that value canbe tested in an <TT>if</TT> statement or by using the conditional operator. You'vealso seen how to evaluate multiple statements using the logical operator, how tocompare values using the relational operators, and how to assign values using theassignment operator.</P><P>You have explored operator precedence. And you have seen how parentheses can beused to change the precedence and to make precedence explicit and thus easier tomanage.<CENTER><H3><A NAME="Heading50"></A><FONT COLOR="#000077">Q&A</FONT></H3></CENTER><DL> <DD><B>Q. Why use unnecessary parentheses when precedence will determine which operators are acted on first?<BR> </B><BR> <B>A.</B> Although it is true that the compiler will know the precedence and that a programmer can look up the precedence order, code that is easy to understand is easier to maintain.<BR> <BR> <B>Q. If the relational operators always return 1 or 0, why are other values considered true?<BR> </B><BR> <B>A. </B>The relational operators return 1 or 0, but every expression returns a value, and those values can also be evaluated in an <TT>if</TT> statement. Here's an example:</DL><PRE><FONT COLOR="#0066FF">if ( (x = a + b) == 35 )</FONT></PRE><DL> <DD>This is a perfectly legal C++ statement. It evaluates to a value even if the sum of <TT>a</TT> and <TT>b</TT> is not equal to 35. Also note that <TT>x</TT> is assigned the value that is the sum of <TT>a</TT> and <TT>b</TT> in any case.<BR> <BR> <B>Q. What effect do tabs, spaces, and new lines have on the program?<BR> </B><BR> A. Tabs, spaces, and new lines (known as whitespace) have no effect on the program, although judicious use of whitespace can make the program easier to read.<BR> <BR> <B>Q. Are negative numbers true or false?<BR> </B><BR> <B>A.</B> All nonzero numbers, positive and negative, are true.</DL><CENTER><H3><A NAME="Heading51"></A><FONT COLOR="#000077">Workshop</FONT></H3></CENTER><P>The Workshop provides quiz questions to help you solidify your understanding ofthe material covered, and exercises to provide you with experience in using whatyou've learned. Try to answer the quiz and exercise questions before checking theanswers in Appendix D, and make sure that you understand the answers before continuingto the next chapter.<CENTER><H4><A NAME="Heading52"></A><FONT COLOR="#000077">Quiz</FONT></H4></CENTER><DL> <DD><B>1.</B> What is an expression?<BR> <B><BR> 2.</B> Is <TT>x = 5 + 7</TT> an expression? What is its value?<BR> <B><BR> 3.</B> What is the value of <TT>201 / 4</TT>?<BR> <B><BR> 4.</B> What is the value of <TT>201 % 4</TT>?<BR> <B><BR> 5.</B> If <TT>myAge</TT>, <TT>a</TT>, and <TT>b</TT> are all <TT>int</TT> variables, what are their values after:</DL><PRE><FONT COLOR="#0066FF">myAge = 39;a = myAge++;b = ++myAge;</FONT></PRE><DL> <DD><B>6.</B> What is the value of <TT>8+2*3</TT>?<BR> <BR> <B>7.</B> What is the difference between <TT>x = 3</TT> and <TT>x == 3</TT>?<BR> <BR> <B>8.</B> Do the following values evaluate to <TT>TRUE</TT> or <TT>FALSE</TT>? <DL> <DD><B><BR> a</B>. <TT>0</TT><BR> <B><BR> b.</B> <TT>1</TT> </DL> <DD> <DL> <DD><B>c.</B> <TT>-1</TT> </DL> <DD> <DL> <DD><B>d.</B> <TT>x</TT> <TT>= 0</TT> </DL> <DD> <DL> <DD><B>e</B>. <TT>x == 0 // assume that x has the value of 0</TT> </DL></DL><CENTER><H4><A NAME="Heading53"></A><FONT COLOR="#000077">Exercises</FONT></H4></CENTER><DL> <DD><B>1.</B> Write a single <TT>if</TT> statement that examines two integer variables and changes the larger to the smaller, using only one <TT>else</TT> clause.<BR> <BR> <B>2. </B>Examine the following program. Imagine entering three numbers, and write what output you expect.</DL><PRE><FONT COLOR="#0066FF">1: #include <iostream.h>2: int main()3: { 4: int a, b, c;5: cout << "Please enter three numbers\n";6: cout << "a: ";7: cin >> a;8: cout << "\nb: ";9: cin >> b;10: cout << "\nc: ";11: cin >> c;12:13: if (c = (a-b))14: {cout << "a: ";15: cout << a;16: cout << "minus b: ";17: cout << b;18: cout << "equals c: ";19: cout << c << endl;}20: else21: cout << "a-b does not equal c: " << endl;22: return 0;23: }</FONT></PRE><DL> <DD><B>3.</B> Enter the program from Exercise 2; compile, link, and run it. Enter the numbers 20, 10, and 50. Did you get the output you expected? Why not?<BR> <BR> <B>4.</B> Examine this program and anticipate the output:</DL><PRE><FONT COLOR="#0066FF">1: #include <iostream.h>2: int main()3: {4: int a = 1, b =
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -