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

📄 ch03.htm

📁 Why C++ is the emerging standard in software development. The steps to develop a C++ program. How
💻 HTM
📖 第 1 页 / 共 4 页
字号:
long</FONT></H3></CENTER><P>One source of confusion for new C++ programmers is when to declare a variableto be type <TT>long</TT> and when to declare it to be type <TT>short</TT>. The rule,when understood, is fairly straightforward: If there is any chance that the valueyou'll want to put into your variable will be too big for its type, use a largertype.</P><P>As seen in Table 3.1, <TT>unsigned short</TT> integers, assuming that they aretwo bytes, can hold a value only up to 65,535. <TT>Signed</TT> <TT>short</TT> integerscan hold only half that. Although <TT>unsigned long</TT> integers can hold an extremelylarge number (4,294,967,295) that is still quite finite. If you need a larger number,you'll have to go to <TT>float</TT> or <TT>double</TT>, and then you lose some precision.Floats and doubles can hold extremely large numbers, but only the first 7 or 19 digitsare significant on most computers. That means that the number is rounded off afterthat many digits.<CENTER><H4><A NAME="Heading23"></A><FONT COLOR="#000077">Wrapping Around an unsigned Integer</FONT></H4></CENTER><P>The fact that <TT>unsigned long</TT> integers have a limit to the values theycan hold is only rarely a problem, but what happens if you do run out of room?</P><P>When an <TT>unsigned</TT> integer reaches its maximum value, it wraps around andstarts over, much as a car odometer might. Listing 3.4 shows what happens if youtry to put too large a value into a <TT>short</TT> integer.</P><P><A NAME="Heading24"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 3.4.A demonstrationof putting too large a value in an unsigned integer.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: #include &lt;iostream.h&gt;2:  int main()3:  {4:     unsigned short int smallNumber;5:     smallNumber = 65535;6:     cout &lt;&lt; &quot;small number:&quot; &lt;&lt; smallNumber &lt;&lt; endl;7:     smallNumber++;8:     cout &lt;&lt; &quot;small number:&quot; &lt;&lt; smallNumber &lt;&lt; endl;9:     smallNumber++;10:    cout &lt;&lt; &quot;small number:&quot; &lt;&lt; smallNumber &lt;&lt; endl;11:        return 0;<TT>12: }</TT>Output: small number:65535small number:0small number:1</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 4, <TT>smallNumber</TT>is declared to be an <TT>unsigned short int</TT>, which on my computer is a two-bytevariable, able to hold a value between 0 and 65,535. On line 5, the maximum valueis assigned to <TT>smallNumber</TT>, and it is printed on line 6. <BR><BR>On line 7, <TT>smallNumber</TT> is incremented; that is, 1 is added to it. The symbolfor incrementing is <TT>++</TT> (as in the name C++--an incremental increase fromC). Thus, the value in <TT>smallNumber</TT> would be <TT>65,536</TT>. However, <TT>unsigned</TT><TT>short</TT> integers can't hold a number larger than 65,535, so the value is wrappedaround to <TT>0</TT>, which is printed on line 8.</P><P>On line 9 <TT>smallNumber</TT> is incremented again, and then its new value, <TT>1</TT>,is printed.<CENTER><H4><A NAME="Heading26"></A><FONT COLOR="#000077">Wrapping Around a signed Integer</FONT></H4></CENTER><P>A <TT>signed</TT> integer is different from an <TT>unsigned</TT> integer, in thathalf of the values you can represent are negative. Instead of picturing a traditionalcar odometer, you might picture one that rotates up for positive numbers and downfor negative numbers. One mile from 0 is either 1 or -1. When you run out of positivenumbers, you run right into the largest negative numbers and then count back downto 0. Listing 3.5 shows what happens when you add 1 to the maximum positive numberin an <TT>unsigned short</TT> integer.</P><P><A NAME="Heading27"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 3.5. A demonstrationof adding too large a number to a signed integer.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:  #include &lt;iostream.h&gt;2:  int main()3:  {4:     short int smallNumber;5:     smallNumber = 32767;6:     cout &lt;&lt; &quot;small number:&quot; &lt;&lt; smallNumber &lt;&lt; endl;7:     smallNumber++;8:     cout &lt;&lt; &quot;small number:&quot; &lt;&lt; smallNumber &lt;&lt; endl;9:     smallNumber++;10:    cout &lt;&lt; &quot;small number:&quot; &lt;&lt; smallNumber &lt;&lt; endl;11:        return 0;<TT>12: }</TT>Output: small number:32767small number:-32768small number:-32767</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis: </B></FONT>On line 4, <TT>smallNumber</TT>is declared this time to be a <TT>signed</TT> <TT>short</TT> integer (if you don'texplicitly say that it is <TT>unsigned</TT>, it is assumed to be <TT>signed</TT>).The program proceeds much as the preceding one, but the output is quite different.To fully understand this output, you must be comfortable with how <TT>signed</TT>numbers are represented as bits in a two-byte integer. For details, check AppendixC, &quot;Binary and Hexadecimal.&quot; <BR><BR>The bottom line, however, is that just like an <TT>unsigned</TT> integer, the <TT>signed</TT>integer wraps around from its highest positive value to its highest negative value.<CENTER><H3><A NAME="Heading29"></A><FONT COLOR="#000077">Characters</FONT></H3></CENTER><P>Character variables (<TT>type char</TT>) are typically 1 byte, enough to hold256 values (see Appendix C). A <TT>char</TT> can be interpreted as a small number(0-255) or as a member of the ASCII set. ASCII stands for the American Standard Codefor Information Interchange. The ASCII character set and its ISO (International StandardsOrganization) equivalent are a way to encode all the letters, numerals, and punctuationmarks.<BLOCKQUOTE>	<P><HR>Computers do not know about letters, punctuation, or sentences. All they understand	are numbers. In fact, all they really know about is whether or not a sufficient amount	of electricity is at a particular junction of wires. If so, it is represented internally	as a <TT>1</TT>; if not, it is represented as a <TT>0</TT>. By grouping ones and	zeros, the computer is able to generate patterns that can be interpreted as numbers,	and these in turn can be assigned to letters and punctuation. <HR></BLOCKQUOTE><P>In the ASCII code, the lowercase letter &quot;a&quot; is assigned the value <TT>97</TT>.All the lower- and uppercase letters, all the numerals, and all the punctuation marksare assigned values between 1 and 128. Another 128 marks and symbols are reservedfor use by the computer maker, although the IBM extended character set has becomesomething of a standard.<CENTER><H4><A NAME="Heading30"></A><FONT COLOR="#000077">Characters and Numbers</FONT></H4></CENTER><P>When you put a character, for example, <TT>`a'</TT>, into a <TT>char</TT> variable,what is really there is just a number between 0 and 255. The compiler knows, however,how to translate back and forth between characters (represented by a single quotationmark and then a letter, numeral, or punctuation mark, followed by a closing singlequotation mark) and one of the ASCII values.</P><P>The value/letter relationship is arbitrary; there is no particular reason thatthe lowercase &quot;a&quot; is assigned the value <TT>97</TT>. As long as everyone(your keyboard, compiler, and screen) agrees, there is no problem. It is importantto realize, however, that there is a big difference between the value <TT>5</TT>and the character <TT>`5'</TT>. The latter is actually valued at <TT>53</TT>, muchas the letter <TT>`a'</TT> is valued at <TT>97</TT>.</P><P><A NAME="Heading31"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 3.6. Printingcharacters based on numbers</B></FONT></P><PRE><FONT COLOR="#0066FF">1:   #include &lt;iostream.h&gt;2:   int main()3:   {4:   for (int i = 32; i&lt;128; i++)5:         cout &lt;&lt; (char) i;6:         return 0;<TT>7: }</TT> Output: !&quot;#$%G'()*+,./0123456789:;&lt;&gt;?@ABCDEFGHIJKLMNOP_QRSTUVWXYZ[\]^'abcdefghijklmnopqrstuvwxyz&lt;|&gt;~s</FONT></PRE><P>This simple program prints the character values for the integers 32 through 127.<CENTER><H4><A NAME="Heading33"></A><FONT COLOR="#000077">Special Printing Characters</FONT></H4></CENTER><P>The C++ compiler recognizes some special characters for formatting. Table 3.2shows the most common ones. You put these into your code by typing the backslash(called the escape character), followed by the character. Thus, to put a tab characterinto your code, you would enter a single quotation mark, the slash, the letter t,and then a closing single quotation mark:</P><PRE><FONT COLOR="#0066FF">char tabCharacter = `\t';</FONT></PRE><P>This example declares a <TT>char</TT> variable (<TT>tabCharacter</TT>) and initializesit with the character value <TT>\t</TT>, which is recognized as a tab. The specialprinting characters are used when printing either to the screen or to a file or otheroutput device.</P><DL>	<DD><HR><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>An <I>escape character</I> changes	the meaning of the character that follows it. For example, normally the character	<TT>n</TT> means the letter n, but when it is preceded by the escape character (<TT>\</TT>)	it means new line. <HR></DL><P><FONT SIZE="4"><B>Table 3.2. The Escape Characters</B></FONT>. <TABLE BORDER="0">	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><B><I>Character</I></B></TD>		<TD ALIGN="LEFT"><B><I>What it means</I></B></TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\n</TT></TD>		<TD ALIGN="LEFT">new line</TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\t</TT></TD>		<TD ALIGN="LEFT">tab</TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\b</TT></TD>		<TD ALIGN="LEFT">backspace</TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\&quot;</TT></TD>		<TD ALIGN="LEFT">double quote</TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\'</TT></TD>		<TD ALIGN="LEFT">single quote</TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\?</TT></TD>		<TD ALIGN="LEFT">question mark</TD>	</TR>	<TR ALIGN="LEFT" rowspan="1">		<TD ALIGN="LEFT"><TT>\\</TT></TD>		<TD ALIGN="LEFT">backslash</TD>	</TR></TABLE><CENTER><H3><A NAME="Heading34"></A><FONT COLOR="#000077">Constants</FONT></H3></CENTER><P>Like variables, constants are data storage locations. Unlike variables, and asthe name implies, constants don't change. You must initialize a constant when youcreate it, and you cannot assign a new value later.<CENTER><H4><A NAME="Heading35"></A><FONT COLOR="#000077">Literal Constants</FONT></H4></CENTER><P>C++ has two types of constants: literal and symbolic.</P><P>A literal constant is a value typed directly into your program wherever it isneeded. For example</P><PRE><FONT COLOR="#0066FF">int myAge = 39;</FONT></PRE><P><TT>myAge</TT> is a variable of type <TT>int</TT>; <TT>39</TT> is a literal constant.You can't assign a value to <TT>39</TT>, and its value can't be changed.<CENTER><H4><A NAME="Heading36"></A><FONT COLOR="#000077">Symbolic Constants</FONT></H4></CENTER><P>A symbolic constant is a constant that is represented by a name, just as a variableis represented. Unlike a variable, however, after a constant is initialized, itsvalue can't be changed.</P><P>If your program has one integer variable named <TT>students</TT> and another named<TT>classes</TT>, you could compute how many students you have, given a known numberof classes, if you knew there were 15 students per class:</P><PRE><FONT COLOR="#0066FF">students = classes * 15;</FONT></PRE><BLOCKQUOTE>	<P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><TT><B> </B>*</TT> indicates multiplication.	<HR></BLOCKQUOTE><P>In this example, <TT>15</TT> is a literal constant. Your code would be easierto read, and easier to maintain, if you substituted a symbolic constant for thisvalue:</P><PRE><FONT COLOR="#0066FF">students = classes * studentsPerClass</FONT></PRE><P>If you later decided to change the number of students in each class, you coulddo so where you define the constant <TT>studentsPerClass</TT> without having to makea change every place you used that value.</P><P>There are two ways to declare a symbolic constant in C++. The old, traditional,and now obsolete way is with a preprocessor directive, <TT>#define</TT>. DefiningConstants with #define To define a constant the traditional way, you would enterthis:</P><PRE><FONT COLOR="#0066FF">#define studentsPerClass 15</FONT></PRE><P>Note that <TT>studentsPerClass</TT> is of no particular type (<TT>int</TT>, <TT>char</TT>,and so on). <TT>#define</TT> does a simple text substitution. Every time the preprocessorsees the word <TT>studentsPerClass</TT>, it puts in the text <TT>15</TT>.</P><P>Because the preprocessor runs before the compiler, your compiler never sees yourconstant; it sees the number <TT>15</TT>. Defining Constants with const Although<TT>#define</TT> works, there is a new, much better way to define constants in C++:</P><PRE><FONT COLOR="#0066FF">const unsigned short int studentsPerClass = 15;</FONT></PRE><P>This example also declares a symbolic constant named <TT>studentsPerClass</TT>,but this time <TT>studentsPerClass</TT> is typed as an <TT>unsigned short int</TT>.This method has several advantages in making your code easier to maintain and inpreventing bugs. The biggest difference is that this constant has a type, and thecompiler can enforce that it is used according to its type.<BLOCKQUOTE>	<P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Constants cannot be changed while	the program is running. If you need to change <TT>studentsPerClass</TT>, for example,	you need to change the code and recompile. <HR></P>

⌨️ 快捷键说明

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