📄 chapter03.html
字号:
<HTML><HEAD> <TITLE>Chapter 3</TITLE> <LINK REL="STYLESHEET" HREF="downey.css" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/downey.css"></HEAD><BODY><H2>Chapter 3</H2><H1>Function</H1><BR><BR><H3>3.1 Floating-point</H3><P>In the last chapter we had some problems dealing with numbers that were notintegers. We worked around the problem by measuring percentages instead of fractions, but a more general solution is to use floating-point numbers, which can represent fractions as well as integers. In C++, there are two floating-point types, called <TT>float</TT> and <TT>double</TT>. In this book we will use <TT>double</TT>s exclusively.</P><P>You can create floating-point variables and assign values to them using the same syntax we used for the other types. For example:</P><PRE> double pi; pi = 3.14159;</PRE><P>It is also legal to declare a variable and assign a value to it at the same time:</P><PRE> int x = 1; String empty = ""; double pi = 3.14159;</PRE><P>In fact, this syntax is quite common. A combined declaration and assignmentis sometimes called an <B>initialization</B>.</P><P>Although floating-point numbers are useful, they are often a source of confusion because there seems to be an overlap between integers and floating-point numbers. For example, if you have the value <TT>1</TT>, is thatan integer, a floating-point number, or both?</P><P>Strictly speaking, C++ distinguishes the integer value <TT>1</TT> from the floating-point value <TT>1.0</TT>, even though they seem to be the same number.They belong to different types, and strictly speaking, you are not allowed to make assignments between types. For example, the following is illegal</P><PRE> int x = 1.1;</PRE><P>because the variable on the left is an <TT>int</TT> and the value on the right is a <TT>double</TT>. But it is easy to forget this rule, especially because there are places where C++ automatically converts from one type to another. For example,</P><PRE> double y = 1;</PRE><P>should technically not be legal, but C++ allows it by converting the <TT>int</TT> to a <TT>double</TT> automatically. This leniency is convenient, but it can cause problems; for example:</P><PRE> double y = 1 / 3;</PRE><P>You might expect the variable <TT>y</TT> to be given the value <TT>0.333333</TT>, which is a legal floating-point value, but in fact it will get the value <TT>0.0</TT>. The reason is that the expression on the right appears to be the ratio of two integers, so C++ does <I>integer</I> division, which yields the integer value <TT>0</TT>. Converted to floating-point, the result is <TT>0.0</TT>.</P><P>One way to solve this problem (once you figure out what it is) is to make the right-hand side a floating-point expression:</P><PRE> double y = 1.0 / 3.0;</PRE><P>This sets <TT>y</TT> to <TT>0.333333</TT>, as expected.</P><P>All the operations we have seen---addition, subtraction, multiplication, and division---work on floating-point values, although you might be interested to know that the underlying mechanism is completely different. In fact, most processors have special hardware just for performing floating-point operations.</P><BR><BR><H3>3.2 Converting from <TT>double</TT> to <TT>int</TT></H3><P>As I mentioned, C++ converts <TT>int</TT>s to <TT>double</TT>s automaticallyif necessary, because no information is lost in the translation. On the other hand, going from a <TT>double</TT> to an <TT>int</TT> requires rounding off.C++ doesn't perform this operation automatically, in order to make sure that you, as the programmer, are aware of the loss of the fractional part of the number.</P><P>The simplest way to convert a floating-point value to an integer is to use a<B>typecast</B>. Typecasting is so called because it allows you to take a value that belongs to one type and ``cast'' it into another type (in the sense of molding or reforming, not throwing).</P><P>The syntax for typecasting is like the syntax for a function call. For example:</P><PRE> double pi = 3.14159; int x = int (pi);</PRE><P>The <TT>int</TT> function returns an integer, so <TT>x</TT> gets the value 3. Converting to an integer always rounds down, even if the fraction part is 0.99999999.</P><P>For every type in C++, there is a corresponding function that typecasts its argument to the appropriate type.</P><BR><BR><H3>3.3 Math functions</H3><P>In mathematics, you have probably seen functions like <TT>sin</TT> and<TT>log</TT>, and you have learned to evaluate expressions like <TT>sin(pi/2)</TT> and <TT>log(1/x)</TT>. First, you evaluate the expression in parentheses, which is called the <B>argument</B> of the function. For example, <TT>pi/2</TT> is approximately 1.571, and <TT>1/x</TT> is 0.1 (if <TT>x</TT> happens to be 10).</P><P>Then you can evaluate the function itself, either by looking it up ina table or by performing various computations. The <TT>sin</TT> of 1.571 is1, and the <TT>log</TT> of 0.1 is -1 (assuming that <TT>log</TT> indicates thelogarithm base 10).</P>This process can be applied repeatedly to evaluate more complicated expressionslike <TT>log(1/sin(pi/2))</TT>. First we evaluate the argument of the innermost function, then evaluate the function, and so on.</P><P>C++ provides a set of built-in functions that includes most of the mathematical operations you can think of. The math functions are invoked using a syntax that is similar to mathematical notation:</P><PRE> double log = log (17.0); double angle = 1.5; double height = sin (angle);</PRE><P>The first example sets <TT>log</TT> to the logarithm of 17, base <TT>e</TT>.There is also a function called <TT>log10</TT> that takes logarithms base 10.</P><P>The second example finds the sine of the value of the variable <TT>angle</TT>. C++ assumes that the values you use with <TT>sin</TT> and the other trigonometric functions (<TT>cos</TT>, <TT>tan</TT>) are in <I>radians</I>. To convert from degrees to radians, you can divide by 360and multiply by <TT>2 pi</TT>.</P> <P>If you don't happen to know <TT>pi</TT> to 15 digits, you can calculate it using the <TT>acos</TT> function. The arccosine (or inverse cosine) of -1 is<TT>pi</TT>, because the cosine of <TT>pi</TT> is -1.</P><PRE> double pi = acos(-1.0); double degrees = 90; double angle = degrees * 2 * pi / 360.0;</PRE><P>Before you can use any of the math functions, you have to include the math <B>header file</B>. Header files contain information the compiler needs about functions that are defined outside your program. For example, in the ``Hello, world!'' program we included a header file named <TT>iostream.h</TT> using an <B>include</B> statement:</P><PRE>#include <iostream.h></PRE><P><TT>iostream.h</TT> contains information about input and output (I/O) streams, including the object named <TT>cout</TT>.</P><P>Similarly, the math header file contains information about the math functions. You can include it at the beginning of your program along with <TT>iostream.h</TT>:</P><PRE>#include <math.h></PRE><BR><BR><H3>3.4 Composition</H3><P>Just as with mathematical functions, C++ functions can be <B>composed</B>, meaning that you use one expression as part of another. For example, you can use any expression as an argument to a function:</P><PRE> double x = cos (angle + pi/2);</PRE><P>This statement takes the value of <TT>pi</TT>, divides it by two and adds the result to the value of <TT>angle</TT>. The sum is then passed as an argument to the <TT>cos</TT> function.</P><P>You can also take the result of one function and pass it as an argument to another:</P><PRE> double x = exp (log (10.0));</PRE><P>This statement finds the log base $e$ of 10 and then raises $e$ to that power. The result gets assigned to <TT>x</TT>; I hope you know what it is.</P><BR><BR><H3>3.5 Adding new functions</H3><P>So far we have only been using the functions that are built into C++, but it is also possible to add new functions. Actually, we have already seen one function definition: <TT>main</TT>. The function named <TT>main</TT> is special because it indicates where the execution of the program begins, but thesyntax for <TT>main</TT> is the same as for any other function definition:</P><PRE> void NAME ( LIST OF PARAMETERS ) { STATEMENTS }</PRE><P>You can make up any name you want for your function, except that you can't call it <TT>main</TT> or any other C++ keyword. The list of parameters specifies what information, if any, you have to provide in order to use (or <B>call</B>) the new function.</P><P><TT>main</TT> doesn't take any parameters, as indicated by the empty parentheses <TT>()</TT> in it's definition. The first couple of functions we are going to write also have no parameters, so the syntax looks like this:</P><PRE> void newLine () { cout << endl; }</PRE><P>This function is named <TT>newLine</TT>; it contains only a single statement,which outputs a newline character, represented by the special value <TT>endl</TT>.</P><P>In <TT>main</TT> we can call this new function using syntax that is similar to the way we call the built-in C++ commands:</P><PRE>void main (){ cout << "First Line." << endl; newLine (); cout << "Second Line." << endl;}</PRE><P>The output of this program is</P><PRE>First line.Second line.</PRE><P>Notice the extra space between the two lines. What if we wanted more space between the lines? We could call the same function repeatedly:</P><PRE>void main (){ cout << "First Line." << endl; newLine (); newLine (); newLine (); cout << "Second Line." << endl;}</PRE><P>Or we could write a new function, named <TT>threeLine</TT>, that prints three new lines:</P><PRE>void threeLine (){ newLine (); newLine (); newLine ();}void main (){ cout << "First Line." << endl; threeLine (); cout << "Second Line." << endl;}</PRE><P>You should notice a few things about this program:</P><UL> <LI>You can call the same procedure repeatedly. In fact, it is quite common and useful to do so.</LI> <LI>You can have one function call another function. In this case, <TT>main</TT> calls <TT>threeLine</TT> and <TT>threeLine</TT> calls <TT>newLine</TT>. Again, this is common and useful.</LI> <LI>In <TT>threeLine</TT> I wrote three statements all on the same line, which is syntactically legal (remember that spaces and new lines usually don't change the meaning of a program). On the other hand, it is usually a better idea to put each statement on a line by itself, to make your program easy to read. I sometimes break that rule in this book to save space. </P></LI></UL><P>So far, it may not be clear why it is worth the trouble to create all these
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -