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

📄 ch03.htm

📁 Why C++ is the emerging standard in software development. The steps to develop a C++ program. How
💻 HTM
📖 第 1 页 / 共 4 页
字号:
	<P><HR><B>DON'T </B>use the term <TT>int</TT>. Use <TT>short</TT> and <TT>long</TT> to make	it clear which size number you intended. <B>DO</B> watch for numbers overrunning	the size of the integer and wrapping around incorrect values. <B>DO</B> give your	variables meaningful names that reflect their use. <B>DON'T </B>use keywords as variable	names. <HR></BLOCKQUOTE><CENTER><H3><A NAME="Heading37"></A><FONT COLOR="#000077">Enumerated Constants</FONT></H3></CENTER><P>Enumerated constants enable you to create new types and then to define variablesof those types whose values are restricted to a set of possible values. For example,you can declare <TT>COLOR</TT> to be an enumeration, and you can define that thereare five values for <TT>COLOR</TT>: <TT>RED</TT>, <TT>BLUE</TT>, <TT>GREEN</TT>,<TT>WHITE</TT>, and <TT>BLACK</TT>.</P><P>The syntax for enumerated constants is to write the keyword <TT>enum</TT>, followedby the type name, an open brace, each of the legal values separated by a comma, andfinally a closing brace and a semicolon. Here's an example:</P><PRE><FONT COLOR="#0066FF">enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };</FONT></PRE><P>This statement performs two tasks:<DL>	<DD><B>1.</B> It makes <TT>COLOR</TT> the name of an enumeration, that is, a new	type.<BR>	<BR>	<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 forth.</DL><P>Every enumerated constant has an integer value. If you don't specify otherwise,the first constant will have the value <TT>0</TT>, and the rest will count up fromthere. Any one of the constants can be initialized with a particular value, however,and those that are not initialized will count upward from the ones before them. Thus,if you write</P><PRE><FONT COLOR="#0066FF">enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };</FONT></PRE><P>then <TT>RED</TT> will have 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>You can define variables of type <TT>COLOR</TT>, but they can be assigned onlyone of the enumerated values (in this case, <TT>RED</TT>, <TT>BLUE</TT>, <TT>GREEN</TT>,<TT>WHITE</TT>, or <TT>BLACK</TT>, or else <TT>100</TT>, <TT>101</TT>, <TT>500</TT>,<TT>501</TT>, or <TT>700</TT>). You can assign any color value to your <TT>COLOR</TT>variable. In fact, you can assign any integer value, even if it is not a legal color,although a good compiler will issue a warning if you do. It is important to realizethat enumerator variables actually are of type <TT>unsigned int</TT>, and that theenumerated constants equate to integer variables. It is, however, very convenientto be able to name these values when working with colors, days of the week, or similarsets of values. Listing 3.7 presents a program that uses an enumerated type.</P><P><A NAME="Heading38"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 3.7. A demonstrationof enumerated constants</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:  #include &lt;iostream.h&gt;2:  int main()3:  {4:       enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,                     &#194;_Saturday };5:6:       Days DayOff;7:       int x;8:9:       cout &lt;&lt; &quot;What day would you like off (0-6)? &quot;;10:      cin  &gt;&gt; x;11:      DayOff = Days(x);12:13:      if (DayOff == Sunday || DayOff == Saturday)14:            cout &lt;&lt; &quot;\nYou're already off on weekends!\n&quot;;15:      else16:            cout &lt;&lt; &quot;\nOkay, I'll put in the vacation day.\n&quot;;17:       return 0;<TT>18: }</TT>Output: What day would you like off (0-6)?  1Okay, I'll put in the vacation day.What day would you like off (0-6)?  0You're already off on weekends!</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 4, the enumeratedconstant <TT>DAYS</TT> is defined, with seven values counting upward from 0. Theuser is prompted for a day on line 9. The chosen value, a number between 0 and 6,is compared on line 13 to the enumerated values for Sunday and Saturday, and actionis taken accordingly. <BR><BR>The <TT>if</TT> statement will be covered in more detail on Day 4, &quot;Expressionsand Statements.&quot;</P><P>You cannot type the word &quot;Sunday&quot; when prompted for a day; the programdoes not know how to translate the characters in <TT>Sunday</TT> into one of theenumerated values.<BLOCKQUOTE>	<P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>For this and all the small programs	in this book, I've left out all the code you would normally write to deal with what	happens when the user types inappropriate data. For example, this program doesn't	check, as it would in a real program, to make sure that the user types a number between	0 and 6. This detail has been left out to keep these programs small and simple, and	to focus on the issue at hand. <HR></BLOCKQUOTE><CENTER><H3><A NAME="Heading40"></A><FONT COLOR="#000077">Summary</FONT></H3></CENTER><P>This chapter has discussed numeric and character variables and constants, whichare used by C++ to store data during the execution of your program. Numeric variablesare either integral (<TT>char</TT>, <TT>short</TT>, and <TT>long int</TT>) or theyare floating point (<TT>float</TT> and <TT>double</TT>). Numeric variables can alsobe <TT>signed</TT> or <TT>unsigned</TT>. Although all the types can be of varioussizes among different computers, the type specifies an exact size on any given computer.</P><P>You must declare a variable before it can be used, and then you must store thetype of data that you've declared as correct for that variable. If you put too largea number into an integral variable, it wraps around and produces an incorrect result.</P><P>This chapter also reviewed literal and symbolic constants, as well as enumeratedconstants, and showed two ways to declare a symbolic constant: using <TT>#define</TT>and using the keyword <TT>const</TT>.<CENTER><H3><A NAME="Heading41"></A><FONT COLOR="#000077">Q&amp;A</FONT></H3></CENTER><DL>	<DD><B>Q. If a short int can run out of room and wrap around, why not always use	long integers?<BR>	</B><BR>	<B>A .</B>Both <TT>short</TT> integers and <TT>long</TT> integers will run out of	room and wrap around, but a <TT>long</TT> integer will do so with a much larger number.	For example, an <TT>unsigned short int</TT> will wrap around after 65,535, whereas	an <TT>unsigned long int</TT> will not wrap around until 4,294,967,295. However,	on most machines, a <TT>long</TT> integer takes up twice as much memory every time	you declare one (4 bytes versus 2 bytes), and a program with 100 such variables will	consume an extra 200 bytes of RAM. Frankly, this is less of a problem than it used	to be, because most personal computers now come with many thousands (if not millions)	of bytes of memory.<BR>	<BR>	<B>Q. What happens if I assign a number with a decimal point to an integer rather	than to a float? Consider the following line of code:</B></DL><PRE><FONT COLOR="#0066FF">int aNumber = 5.4;</FONT></PRE><DL>	<DD><B>A.</B> A good compiler will issue a warning, but the assignment is completely	legal. The number you've assigned will be truncated into an integer. Thus, if you	assign <TT>5.4</TT> to an integer variable, that variable will have the value <TT>5</TT>.	Information will be lost, however, and if you then try to assign the value in that	integer variable to a <TT>float</TT> variable, the <TT>float</TT> variable will have	only <TT>5</TT>.<BR>	<BR>	<B>Q. Why not use literal constants; why go to the bother of using symbolic constants?<BR>	</B><BR>	<B>A.</B> If you use the value in many places throughout your program, a symbolic	constant allows all the values to change just by changing the one definition of the	constant. Symbolic constants also speak for themselves. It might be hard to understand	why a number is being multiplied by 360, but it's much easier to understand what's	going on if the number is being multiplied by <TT>degreesInACircle</TT>.<BR>	<BR>	<B>Q. What happens if I assign a negative number to an unsigned variable? Consider	the following line of code:</B></DL><PRE><FONT COLOR="#0066FF">unsigned int aPositiveNumber = -1;</FONT></PRE><DL>	<DD><B>A.</B> A good compiler will warn, but the assignment is legal. The negative	number will be assessed as a bit pattern and assigned to the variable. The value	of that variable will then be interpreted as an <TT>unsigned</TT> number. Thus, -1,	whose bit pattern is <TT>11111111 11111111</TT> (<TT>0xFF</TT> in hex), will be assessed	as the <TT>unsigned</TT> value <TT>65,535</TT>. If this information confuses you,	refer to Appendix C.<BR>	<BR>	<B>Q. Can I work with C++ without understanding bit patterns, binary arithmetic,	and hexadecimal?</B><BR>	<BR>	<B>A.</B> Yes, but not as effectively as if you do understand these topics. C++ does	not do as good a job as some languages at &quot;protecting&quot; you from what the	computer is really doing. This is actually a benefit, because it provides you with	tremendous power that other languages don't. As with any power tool, however, to	get the most out of C++ you must understand how it works. Programmers who try to	program in C++ without understanding the fundamentals of the binary system often	are confused by their results.</DL><CENTER><H3><A NAME="Heading42"></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="Heading43"></A><FONT COLOR="#000077">Quiz</FONT></H4></CENTER><DL>	<DD><B>1.</B> What is the difference between an integral variable and a floating-point	variable?<BR>	<BR>	<B>2.</B> What are the differences between an <TT>unsigned short int</TT> and a <TT>long	int</TT>?<BR>	<BR>	<B>3.</B> What are the advantages of using a symbolic constant rather than a literal	constant?<BR>	<BR>	<B>4.</B> What are the advantages of using the <TT>const</TT> keyword rather than	<TT>#define</TT>?<BR>	<BR>	<B>5.</B> What makes for a good or bad variable name?<BR>	<BR>	<B>6.</B> Given this <TT>enum</TT>, what is the value of <TT>BLUE</TT>?</DL><PRE><FONT COLOR="#0066FF">enum COLOR { WHITE, BLACK = 100, RED, BLUE, GREEN = 300 };</FONT></PRE><DL>	<DD><B>7.</B> Which of the following variable names are good, which are bad, and	which are invalid?	<DL>		<DD><B><BR>		a.</B> <TT>Age</TT><BR>		<B><BR>		b.</B> <TT>!ex</TT><BR>		<B><BR>		c.</B><TT> R79J</TT><BR>		<B><BR>		d.</B><TT> TotalIncome<BR>		</TT><B><BR>		e.</B> <TT>__Invalid</TT>	</DL></DL><CENTER><H4><A NAME="Heading44"></A><FONT COLOR="#000077">Exercises</FONT></H4></CENTER><DL>	<DD><B>1.</B> What would be the correct variable type in which to store the following	information?	<DL>		<DD><BR>		<B>a.</B> Your age.<BR>		<BR>		<B>b.</B> The area of your backyard.<BR>		<BR>		<B>c.</B> The number of stars in the galaxy.<BR>		<BR>		<B>d.</B> The average rainfall for the month of January.	</DL>	<DD><BR>	<B>2.</B> Create good variable names for this information.<BR>	<BR>	<B>3.</B> Declare a constant for pi as 3.14159.<BR>	<BR>	<B>4.</B> Declare a <TT>float</TT> variable and initialize it using your pi constant.<BR>		<CENTER>	<DD><A HREF="ch02.htm"><IMG SRC="../buttons/BLANPREV.GIF" WIDTH="37"	HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="http://www.mcp.com/sams"><IMG	SRC="../buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM"	BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../buttons/BLANTOC.GIF"	WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch04.htm"><IMG SRC="../buttons/BLANNEXT.GIF"	WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="#heading1"><IMG SRC="../buttons/BLANTOP.GIF"	WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A></CENTER></DL></BODY></HTML>

⌨️ 快捷键说明

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