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

📄 chapter1.html

📁 c语言编程-c语言作者的书。英文原版。非常好。
💻 HTML
📖 第 1 页 / 共 5 页
字号:
a program looks, proper indentation and spacing are critical in makingprograms easy for people to read. We recommend writing only one statement perline, and using blanks around operators to clarify grouping. The position ofbraces is less important, although people hold passionate beliefs. We havechosen one of several popular styles. Pick a style that suits you, then useit consistently.<p>Most of the work gets done in the body of the loop. The Celsius temperatureis computed and assigned to the variable <tt>celsius</tt> by the statement<pre>        celsius = 5 * (fahr-32) / 9;</pre>The reason for multiplying by 5 and dividing by 9 instead of just multiplyingby <tt>5/9</tt> is that in C, as in many other languages, integer division<em> truncates</em>: any fractional part is discarded. Since <tt>5</tt> and<tt>9</tt> are integers. <tt>5/9</tt> would be truncated to zero and so allthe Celsius temperatures would be reported as zero.<p>This example also shows a bit more of how <tt>printf</tt> works. <tt>printf</tt>is a general-purpose output formatting function, which we will describe indetail in <a href="chapter7.html">Chapter 7</a>. Its first argument is a stringof characters to be printed, with each <tt>%</tt> indicating where one of theother (second, third, ...) arguments is to be substituted, and in what formit is to be printed. For instance, <tt>%d</tt> specifies an integer argument,so the statement<pre>        printf("%d\t%d\n", fahr, celsius);</pre>causes the values of the two integers <tt>fahr</tt> and <tt>celsius</tt> to beprinted, with a tab (<tt>\t</tt>) between them.<p>Each <tt>%</tt> construction in the first argument of <tt>printf</tt> is pairedwith the corresponding second argument, third argument, etc.; they must matchup properly by number and type, or you will get wrong answers.<p>By the way, <tt>printf</tt> is not part of the C language; there is no input oroutput defined in C itself. <tt>printf</tt> is just a useful function from thestandard library of functions that are normally accessible to C programs. Thebehaviour of <tt>printf</tt> is defined in the ANSI standard, however, so itsproperties should be the same with any compiler and library that conforms tothe standard.<p>In order to concentrate on C itself, we don't talk much about input andoutput until <a href="chapter7.html">chapter 7</a>. In particular, we willdefer formatted input until then. If you have to input numbers, read thediscussion of the function <tt>scanf</tt> in<a href="chapter7.html#s7.4">Section 7.4</a>. <tt>scanf</tt> is like<tt>printf</tt>, except that it reads input instead of writing output.<p>There are a couple of problems with the temperature conversion program. Thesimpler one is that the output isn't very pretty because the numbers are notright-justified. That's easy to fix; if we augment each <tt>%d</tt> in the<tt>printf</tt> statement with a width, the numbers printed will be right-justifiedin their fields. For instance, we might say<pre>   printf("%3d %6d\n", fahr, celsius);</pre>to print the first number of each line in a field three digits wide, and thesecond in a field six digits wide, like this:<pre>     0     -17    20      -6    40       4    60      15    80      26   100      37   ...</pre>The more serious problem is that because we have used integer arithmetic, theCelsius temperatures are not very accurate; for instance, 0<sup>o</sup>F isactually about -17.8<sup>o</sup>C, not -17. To get more accurate answers, weshould use floating-point arithmetic instead of integer. This requires somechanges in the program. Here is the second version:<pre>   #include &lt;stdio.h&gt;   /* print Fahrenheit-Celsius table       for fahr = 0, 20, ..., 300; floating-point version */   main()   {     float fahr, celsius;     float lower, upper, step;     lower = 0;      /* lower limit of temperatuire scale */     upper = 300;    /* upper limit */     step = 20;      /* step size */     fahr = lower;     while (fahr &lt;= upper) {         celsius = (5.0/9.0) * (fahr-32.0);         printf("%3.0f %6.1f\n", fahr, celsius);         fahr = fahr + step;     }   }</pre>This is much the same as before, except that <tt>fahr</tt> and <tt>celsius</tt>are declared to be <tt>float</tt> and the formula for conversion is written in amore natural way. We were unable to use <tt>5/9</tt> in the previous versionbecause integer division would truncate it to zero. A decimal point in aconstant indicates that it is floating point, however, so <tt>5.0/9.0</tt> isnot truncated because it is the ratio of two floating-point values.<p>If an arithmetic operator has integer operands, an integer operation isperformed. If an arithmetic operator has one floating-point operand and oneinteger operand, however, the integer will be converted to floating pointbefore the operation is done. If we had written <tt>(fahr-32)</tt>, the <tt>32</tt>would be automatically converted to floating point. Nevertheless, writingfloating-point constants with explicit decimal points even when they haveintegral values emphasizes their floating-point nature for human readers.<p>The detailed rules for when integers are converted to floating point are in<a href="chapter2.html">Chapter 2</a>. For now, notice that the assignment<pre>   fahr = lower;</pre>and the test<pre>   while (fahr &lt;= upper)</pre>also work in the natural way - the <tt>int</tt> is converted to <tt>float</tt>before the operation is done.<p>The <tt>printf</tt> conversion specification <tt>%3.0f</tt> says that afloating-point number (here <tt>fahr</tt>) is to be printed at least threecharacters wide, with no decimal point and no fraction digits. <tt>%6.1f</tt>describes another number (<tt>celsius</tt>) that is to be printed at least sixcharacters wide, with 1 digit after the decimal point. The output looks likethis:<pre>     0   -17.8    20    -6.7    40     4.4   ...</pre>Width and precision may be omitted from a specification: <tt>%6f</tt> says thatthe number is to be at least six characters wide; <tt>%.2f</tt> specifies twocharacters after the decimal point, but the width is not constrained; and<tt>%f</tt> merely says to print the number as floating point.<p><table align="center" border=1><td>&nbsp;<tt>%d</tt>   </td><td>&nbsp;print as decimal integer</td><tr><td>&nbsp;<tt>%6d</tt>  </td><td>&nbsp;print as decimal integer, at least 6 characters wide</td><tr><td>&nbsp;<tt>%f</tt>   </td><td>&nbsp;print as floating point</td><tr><td>&nbsp;<tt>%6f</tt>  </td><td>&nbsp;print as floating point, at least 6 characters wide</td><tr><td>&nbsp;<tt>%.2f</tt> </td><td>&nbsp;print as floating point, 2 characters after decimal point</td><tr><td>&nbsp;<tt>%6.2f</tt>&nbsp;&nbsp;</td><td>&nbsp;print as floating point, at least 6 wide and 2 after decimal point&nbsp;</td></table><p>Among others, <tt>printf</tt> also recognizes <tt>%o</tt> for octal, <tt>%x</tt>for hexadecimal, <tt>%c</tt> for character, <tt>%s</tt> for character string and<tt>%%</tt> for itself.<p><strong>Exercise 1-3.</strong> Modify the temperature conversion program to print aheading above the table.<p><strong>Exercise 1-4.</strong> Write a program to print the corresponding Celsius toFahrenheit table.<h2><a name="s1.3">1.3 The for statement</a></h2>There are plenty of different ways to write a program for a particular task.Let's try a variation on the temperature converter.<pre>   #include &lt;stdio.h&gt;   /* print Fahrenheit-Celsius table */   main()   {       int fahr;       for (fahr = 0; fahr &lt;= 300; fahr = fahr + 20)           printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));   }</pre>This produces the same answers, but it certainly looks different. One majorchange is the elimination of most of the variables; only <tt>fahr</tt> remains,and we have made it an <tt>int</tt>. The lower and upper limits and the stepsize appear only as constants in the <tt>for</tt> statement, itself a newconstruction, and the expression that computes the Celsius temperature nowappears as the third argument of <tt>printf</tt> instead of a separateassignment statement.<p>This last change is an instance of a general rule - in any context where itis permissible to use the value of some type, you can use a more complicatedexpression of that type. Since the third argument of <tt>printf</tt> must bea floating-point value to match the <tt>%6.1f</tt>, any floating-pointexpression can occur here.<p>The <tt>for</tt> statement is a loop, a generalization of the <tt>while</tt>.If you compare it to the earlier <tt>while</tt>, its operation should be clear.Within the parentheses, there are three parts, separated by semicolons. Thefirst part, the initialization<pre>   fahr = 0</pre>is done once, before the loop proper is entered. The second part is the testor condition that controls the loop:<pre>   fahr &lt;= 300</pre>This condition is evaluated; if it is true, the body of the loop (here asingle <tt>ptintf</tt>) is executed. Then the increment step<pre>   fahr = fahr + 20</pre>is executed, and the condition re-evaluated. The loop terminates if thecondition has become false. As with the <tt>while</tt>, the body of the loop canbe a single statement or a group of statements enclosed in braces. Theinitialization, condition and increment can be any expressions.<p>The choice between <tt>while</tt> and <tt>for</tt> is arbitrary, based on whichseems clearer. The <tt>for</tt> is usually appropriate for loops in which theinitialization and increment are single statements and logically related,since it is more compact than <tt>while</tt> and it keeps the loop controlstatements together in one place.<p><strong>Exercise 1-5.</strong> Modify the temperature conversion program toprint the table in reverse order, that is, from 300 degrees to 0.<h2><a name="s1.4">1.4 Symbolic Constants</a></h2>A final observation before we leave temperature conversion forever. It's badpractice to bury ``magic numbers'' like 300 and 20 in a program; they conveylittle information to someone who might have to read the program later, andthey are hard to change in a systematic way. One way to deal with magicnumbers is to give them meaningful names. A <tt>#define</tt> line defines a<em>symbolic name or symbolic constant</em> to be a particular string ofcharacters:<p>&nbsp;&nbsp;<tt>#define</tt>   <em>name   replacement list</em><p>Thereafter, any occurrence of <em>name</em> (not in quotes and not part ofanother name) will be replaced by the corresponding <em>replacement text</em>.The <em>name</em> has the same form as a variable name: a sequence of lettersand digits that begins with a letter. The <em>replacement text</em> can be anysequence of characters; it is not limited to numbers.<pre>   #include &lt;stdio.h&gt;   #define LOWER  0     /* lower limit of table */   #define UPPER  300   /* upper limit */   #define STEP   20    /* step size */   /* print Fahrenheit-Celsius table */   main()   {       int fahr;       for (fahr = LOWER; fahr &lt;= UPPER; fahr = fahr + STEP)           printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));   }</pre>The quantities <tt>LOWER</tt>, <tt>UPPER</tt> and <tt>STEP</tt> are symbolicconstants, not variables, so they do not appear in declarations. Symbolicconstant names are conventionally written in upper case so they can berreadily distinguished from lower case variable names. Notice that there is nosemicolon at the end of a <tt>#define</tt> line.<h2><a name="s1.5">1.5 Character Input and Output</a></h2>We are going to consider a family of related programs for processingcharacter data. You will find that many programs are just expanded versionsof the prototypes that we discuss here.<p>The model of input and output supported by the standard library is verysimple. Text input or output, regardless of where it originates or where itgoes to, is dealt with as streams of characters. A <em>text stream</em> is asequence of characters divided into lines; each line consists of zero or morecharacters followed by a newline character. It is the responsibility of thelibrary to make each input or output stream confirm this model; the Cprogrammer using the library need not worry about how lines are representedoutside the program.<p>The standard library provides several functions for reading or writing onecharacter at a time, of which <tt>getchar</tt> and <tt>putchar</tt> are thesimplest. Each time it is called, <tt>getchar</tt> reads the <em>next inputcharacter</em> from a text stream and returns that as its value. That is, after<pre>   c = getchar();</pre>the variable <tt>c</tt> contains the next character of input. The charactersnormally come from the keyboard; input from files is discussed in<a href="chapter7.html">Chapter 7</a>.<p>The function <tt>putchar</tt> prints a character each time it is called:<pre>   putchar(c);</pre>prints the contents of the integer variable <tt>c</tt> as a character, usuallyon the screen. Calls to <tt>putchar</tt> and <tt>printf</tt> may be interleaved;the output will appear in the order in which the calls are made.<h3><a name="s1.5.1">1.5.1 File Copying</a></h3>Given <tt>getchar</tt> and <tt>putchar</tt>, you can write a surprisingamount of useful code without knowing anything more about input and output.The simplest example is a program that copies its input to its output onecharacter at a time:<pre><em>read a character</em>    while (<em>charater is not end-of-file indicator</em>)        <em>output the character just read        read a character</em></pre>Converting this into C gives:<pre>   #include &lt;stdio.h&gt;   /* copy input to output; 1st version  */   main()

⌨️ 快捷键说明

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