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

📄 007.htm

📁 21天内快速掌握c++语言
💻 HTM
📖 第 1 页 / 共 5 页
字号:
10:    cin >> number;
11:    switch (number)
12:    {
13:       case 0:   cout << "Too small, sorry!";
14:                 break;
15:       case 5:  cout << "Good job!\n";  // fall through
16:       case 4:  cout << "Nice Pick!\n"; // fall through
17:       case 3:  cout << "Excellent!\n"; // fall through
18:       case 2:  cout << "Masterful!\n"; // fall through
19:       case 1:  cout << "Incredible!\n";
20:                break;
21:       default: cout << "Too large!\n";
22:                break;
23:    }
24:    cout << "\n\n";
25:     return 0;
<TT>26: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Enter a number between 1 and 5: 3
Excellent!
Masterful!
Incredible!
<BR>
Enter a number between 1 and 5: 8
Too large!
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The user is prompted for
a number. That number is given to the <TT>switch</TT> statement. If the number is
0, the <TT>case</TT> statement on line 13 matches, the message <TT>Too small, sorry!</TT>
is printed, and the <TT>break</TT> statement ends the switch. If the value is <TT>5</TT>,
execution switches to line 15 where a message is printed, and then falls through
to line 16, another message is printed, and so forth until hitting the <TT>break</TT>
on line 20.<BR>
The net effect of these statements is that for a number between 1 and 5, that many
messages are printed. If the value of number is not 0-5, it is assumed to be too
large, and the <TT>default</TT> statement is invoked on line 21.
<H3 ALIGN="CENTER"><A NAME="Heading57"></A><FONT COLOR="#000077">The switch Statement</FONT></H3>
<P>The syntax for the <TT>switch</TT> statement is as follows:</P>
<PRE><FONT COLOR="#0066FF" font style="font-size:10pt">switch (expression)
{
case valueOne: statement;
case valueTwo: statement;
....
case valueN: statement
default: statement;
}
</FONT></PRE>
<P>The <TT>switch</TT> statement allows for branching on multiple values of expression.
The expression is evaluated, and if it matches any of the <TT>case</TT> values, execution
jumps to that line. Execution continues until either the end of the <TT>switch</TT>
statement or a <TT>break</TT> statement is encountered. If expression does not match
any of the <TT>case</TT> statements, and if there is a <TT>default</TT> statement,
execution switches to the <TT>default</TT> statement, otherwise the <TT>switch</TT>
statement ends. Example 1</P>
<PRE><FONT COLOR="#0066FF" font style="font-size:10pt">switch (choice)
{
case 0:
cout &lt;&lt; &quot;Zero!&quot; &lt;&lt; endl;
break
case 1:
cout &lt;&lt; &quot;One!&quot; &lt;&lt; endl;
break;
case 2:
cout &lt;&lt; &quot;Two!&quot; &lt;&lt; endl;
default:
cout &lt;&lt; &quot;Default!&quot; &lt;&lt; endl;
}
</FONT></PRE>
<P>Example 2</P>
<PRE><FONT COLOR="#0066FF" font style="font-size:10pt">switch (choice)
{
choice 0:
choice 1:
choice 2:
cout &lt;&lt; &quot;Less than 3!&quot;;
break;
choice 3:
cout &lt;&lt; &quot;Equals 3!&quot;;
break;
default:
cout &lt;&lt; &quot;greater than 3!&quot;;
}
</FONT></PRE>
<H4 ALIGN="CENTER"><A NAME="Heading58"></A><FONT COLOR="#000077">Using a switch Statement
with a Menu</FONT></H4>
<P>Listing 7.17 returns to the <TT>for(;;)</TT> loop discussed earlier. These loops
are also called forever loops, as they will loop forever if a <TT>break</TT> is not
encountered. The forever loop is used to put up a menu, solicit a choice from the
user, act on the choice, and then return to the menu. This will continue until the
user chooses to exit.
<BR>
<BR>
<BLOCKQUOTE>
	<P>
<HR>
<FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Some programmers like to write
<HR>
<BR>
<BR>
</BLOCKQUOTE>
<BR>
<PRE><FONT COLOR="#0066FF" font style="font-size:10pt">#define EVER ;;
for (EVER)
{
// statements...
}
</FONT></PRE>
<P>Using <TT>#define</TT> is covered on Day 17, &quot;The Preprocessor.&quot;
<BR>
<DL>
	<DD>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>forever loop</I> is a loop
	that does not have an exit condition. In order to exit the loop, a <TT>break</TT>
	statement must be used. Forever loops are also known as eternal loops.
<HR>
<BR>
</DL>
<BR>
<P><A NAME="Heading59"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.17. Demonstrating
a forever loop.</B></FONT></P>
<PRE><FONT COLOR="#0066FF" font style="font-size:10pt">1:    //Listing 7.17
2:    //Using a forever loop to manage
3:    //user interaction
4:    #include &lt;iostream.h&gt;
5:
6:    // types &amp; defines
7:    enum BOOL { FALSE, TRUE };
8:    typedef unsigned short int USHORT;
9:
10:    // prototypes
11:    USHORT menu();
12:    void DoTaskOne();
13:    void DoTaskMany(USHORT);
14:
15:    int main()
16:    {
17:
18:        BOOL exit = FALSE;
19:        for (;;)
20:        {
21:             USHORT choice = menu();
22:             switch(choice)
23:             {
24:                case (1):
25:                     DoTaskOne();
26:                     break;
27:                case (2):
28:                     DoTaskMany(2);
29:                     break;
30:                case (3):
31:                     DoTaskMany(3);
32:                     break;
33:                case (4):
34:                     continue;  // redundant!
35:                     break;
36:                case (5):
37:                     exit=TRUE;
38:                     break;
39:                default:
40:                     cout &lt;&lt; &quot;Please select again!\n&quot;;
41:                     break;
42:             }          // end switch
43:
44:             if (exit)
45:                    break;
46:        }                // end forever
47:       return 0;
48:    }                    // end main()
49:
50:    USHORT menu()
51:    {
52:        USHORT choice;
53:
54:        cout &lt;&lt; &quot; **** Menu ****\n\n&quot;;
55:        cout &lt;&lt; &quot;(1) Choice one.\n&quot;;
56:        cout &lt;&lt; &quot;(2) Choice two.\n&quot;;
57:        cout &lt;&lt; &quot;(3) Choice three.\n&quot;;
58:        cout &lt;&lt; &quot;(4) Redisplay menu.\n&quot;;
59:        cout &lt;&lt; &quot;(5) Quit.\n\n&quot;;
60:        cout &lt;&lt; &quot;: &quot;;
61:        cin &gt;&gt; choice;
62:        return choice;
63:    }
64:
65:    void DoTaskOne()
66:    {
67:        cout &lt;&lt; &quot;Task One!\n&quot;;
68:    }
69:
70:    void DoTaskMany(USHORT which)
71:    {
72:        if (which == 2)
73:             cout &lt;&lt; &quot;Task Two!\n&quot;;
74:        else
75:             cout &lt;&lt; &quot;Task Three!\n&quot;;
<TT>76: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: **** Menu ****
<BR>
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.
(5) Quit.
<BR>
: 1
Task One!
**** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.
(5) Quit.
<BR>
: 3
Task Three!
**** Menu ****
(1) Choice one.
(2) Choice two.
(3) Choice three.
(4) Redisplay menu.
(5) Quit.
<BR>
: 5
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>This program brings together
a number of concepts from today and previous days. It also shows a common use of
the <TT>switch</TT> statement. On line 7, an enumeration, <TT>BOOL</TT>, is created,
with two possible values: <TT>FALSE</TT>, which equals <TT>0</TT>, as it should,
and <TT>TRUE</TT>, which equals <TT>1</TT>. On line 8, <TT>typedef</TT> is used to
create an alias, <TT>USHORT</TT>, for <TT>unsigned short int</TT>.<BR>
The forever loop begins on 19. The <TT>menu()</TT> function is called, which prints
the menu to the screen and returns the user's selection. The <TT>switch</TT> statement,
which begins on line 22 and ends on line 42, switches on the user's choice.</P>
<P>If the user enters <TT>1</TT>, execution jumps to the <TT>case 1:</TT> statement
on line 24. Line 25 switches execution to the <TT>DoTaskOne()</TT> function, which
prints a message and returns. On its return, execution resumes on line 26, where
the <TT>break</TT> ends the <TT>switch</TT> statement, and execution falls through
to line 43. On line 44, the variable <TT>exit</TT> is evaluated. If it evaluates
<TT>true</TT>, the break on line 45 will be executed and the <TT>for(;;)</TT> loop
will end, but if it evaluates <TT>false</TT>, execution resumes at the top of the
loop on line 19.</P>
<P>Note that the <TT>continue</TT> statement on line 34 is redundant. If it were
left out and the <TT>break</TT> statement were encountered, the <TT>switch</TT> would
end, <TT>exit</TT> would evaluate <TT>FALSE</TT>, the loop would reiterate, and the
menu would be reprinted. The <TT>continue</TT> does, however, bypass the test of
<TT>exit</TT>.
<BR>
<BR>
<BLOCKQUOTE>
	<P>
<HR>
<B>DO</B> use <TT>switch</TT> statements to avoid deeply nested <TT>if</TT> statements.
	<B>DON'T</B> forget <TT>break</TT> at the end of each <TT>case</TT> unless you wish
	to fall through.<B> DO </B>carefully document all intentional fall-through <TT>cases</TT>.
	<B>DO </B>put a default <TT>case</TT> in <TT>switch</TT> statements, if only to detect
	seemingly impossible situations.
<HR>
<BR>
<BR>
</BLOCKQUOTE>
<BR>
<H3 ALIGN="CENTER"><A NAME="Heading61"></A><FONT COLOR="#000077">Summary</FONT></H3>
<P>There are different ways to cause a C++ program to loop. <TT>While</TT> loops
check a condition, and if it is true, execute the statements in the body of the loop.
<TT>do...while</TT> loops execute the body of the loop and then test the condition.
<TT>for</TT> loops initialize a value, then test an expression. If an expression
is true, the final statement in the <TT>for</TT> header is executed, as is the body
of the loop. Each subsequent time through the loop the expression is tested again.</P>
<P>The <TT>goto</TT> statement is generally avoided, as it causes an unconditional
jump to a seemingly arbitrary location in the code, and thus makes source code difficult
to understand and maintain. <TT>continue</TT> causes <TT>while</TT>, <TT>do...while</TT>,
and <TT>for</TT> loops to start over, and <TT>break</TT> causes <TT>while</TT>, <TT>do...while</TT>,
<TT>for</TT>, and <TT>switch</TT> statements to end.
<H3 ALIGN="CENTER"><A NAME="Heading62"></A><FONT COLOR="#000077">Q&amp;A</FONT></H3>
<BR>
<DL>
	<DD><B>Q. How do you choose between if/else and switch?<BR>
	</B><BR>
	<B>A.</B> If there are more than just one or two <TT>else</TT> clauses, and all are
	testing the same value, consider using a <TT>switch</TT> statement.<BR>
	<BR>
	<B>Q. How do you choose between while and do...while?<BR>
	</B><BR>
	<B>A.</B> If the body of the loop should always execute at least once, consider a
	<TT>do...while</TT> loop; otherwise, try to use the <TT>while</TT> loop.<BR>
	<BR>
	<B>Q. How do you choose between while and for?<BR>
	</B><BR>
	<B>A</B> If you are initializing a counting variable, testing that variable, and
	incrementing it each time through the loop, consider the <TT>for</TT> loop. If your
	va

⌨️ 快捷键说明

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