• 沒有找到結果。

* File: add2f.c

* ---

* This program reads in two floating-point numbers, adds them

* together, and prints their sum.

*/

#include <stdio.h>

#include “genlib.h”

#include “simpio.h”

main() {

double n1, n2, total;

printf(“This program adds two floating-point numbers.\n”);

printf(“1st number? “);

n1 = GetReal();

Printf(“2nd number? “);

n2 = GetReal();

total = n1 + n2;

printf(“The total is %g\n”, total):

}

String data

Although the first computers were designed primarily to solve numeric problems (and computers are still sometimes called ―number crunchers‖ as a result), modern computers spend less of their time working with numbers than they do with text. Because the operations on numbers are so simple, the programming examples in the first few chapters

1 This particular type is called double-precision because it offers twice as much accuracy as the floating-point type float, which was much more commonly used when C was first developed. Today, most programmers tend to use the type double for all floating-point values.

of this book concentrate on numeric data. In practice, however, it is very important to be able to manipulate text data as well.

The most primitive elements of text data are individual characters. Characters, however, are most useful when they are collected together into sequential units. In programming, a sequence of characters is called a string. Strings make it possible to display informational messages on the screen. You have already seen several examples of strings in the example programs, beginning with hello.c. It is important, however, to recognize that strings are data and that they can be manipulated and stored in much the same way that numbers can.

When considered in detail, strings turn out to be a complicated data type for which a full treatment lies well beyond the scope of this chapter. Even so, it is useful to know a little about strings at this point for two reasons. First, strings provide an example of a data type that is quite different from either int or double. Because they both refer to numbers and use the same basic set of arithmetic operations, the types int and double are in fact quite similar. Strings are sued in very different ways. Second, strings make it possible to write more interesting programs, even if you do not yet know how to manipulate them in a very sophisticated way.

To use string data at all, you need a way to name the data type. Although the designers of C provided several operations that work with strings in the libraries associated with the language, they did not define and explicit string type. This omission poses a problem for the student programmer. To make up for this deficiency, however, the type string is defined in the header file genlib.h.

The details of the definition for string are not important at this point, provided you know how objects of type string behave. Moreover, it doesn’t matter whether string is defined as part of the language or as part of a library. Types defined in libraries simply become part of the repertoire of data types and are used just as built-in types are. In your programming, you should think of the type string as if it were an integral part of C, even though you know it is actually defined by the genlib library.

You can declare variables of type string in the same way that you declared variables of type int or double in earlier programs. For example, if you want to keep track of someone’s name, which consists of a sequence of characters and is therefore a string, you could write the declaration

string name;

at the beginning of your program.

For the moment, we will not define any operations on strings other than the ones necessary to read them from the keyboard and display them on the screen. Reading in a string is handled in much the same way as reading in a number. The simpio library contains a function GetLine that reads in an entire line and returns it as a string. Given a value of type string, you can use printf to display it on the screen, just as you do with number data. The only difference is that you need to use the format code %s instead of the %d or %g you use for numeric types. These two string operations, by themselves, provide you with a great deal of additional power. For example, you can make a small extension to the ―Hello world‖ program so that it offers a more personal welcome than the generic greeting provided by hello.c. The new version is shown in Figure 2-4.

FIGURE 2-4

greeting.c /*

* File: greeting.c

* ---

* This program prints a more personal greeting than did

* the original “Hello, world.” program by reading in the

* name of the user.

*/

#include <stdio.h>

#include “genlib.h”

#include “simpio.h”

main() {

string user;

printf(“What is your name? “);

user = GetLine();

printf(“Hello, %s.\n”, user):

}

If you run this program using my first name, you would get the following sample run:

Strings are so important to programming that this book devotes several chapters to them.

You will have a chance to learn more about strings beginning in Chapter 9.

1-5 Expressions

Whenever you want a program to perform calculations, you write an expression that specifies the necessary operations in a form similar to that used for expressions in mathematics. For example, to add the values in the variables n1 and n2 in the add2.c program, the appropriate expression is

n1 + n2;

In C, an expression is composed of terms and operators. A term, such as n1 and n2 in the previous expression, represents a single data value. An operator, such as the + sign, is a character (or sometimes a short sequence of characters) that indicates a computational operation. In an expression, a term must be one of the following:

A constant. Any explicit data value that appears as part of the text of the program is called a constant. Numbers such as 0 or 3.14159 are examples of constants.

A variable. Variable serve as placeholders for data that can change during the execution of a program.

A function call. Values are often generated by calling other functions, possibly in libraries, that return data values to the original expression. In the add2.c program, the function GetInteger is used to read in each of the input values; the function call

What is your name? Eric

Hello, Eric.

GetInteger() is therefore an example of a term. Function calls are discussed further in Chapter 5.

An expression in parentheses. Parentheses may be use in an expression to indicate the order of operations, in the same way they are used in mathematics.

From the compiler’s point of view, the expression in parentheses becomes a term that must be handled as a unit before computation can proceed.

When a program is run, the process of performing each of the specified operations in an expression is called evaluation. When an expression is evaluated, each operator is applied to the data values represented by the surrounding terms. After all the operators have been evaluated, what remains is a single data value that indicates the result of the computation.

For example, given the expression n1 + n2

the evaluation process consists of taking the values in the variables n1 and n2 and adding them together, and the result of the result of the evaluation is whatever that sum happens to be.

Constants

When you write a formula in mathematics, some symbols in the formula typically represent unknown values while other symbols represent constants whose values are known. Consider, for example, the mathematical formula for computing the circumference (C) of a circle given its radius (r):

C = 2πr

To translate this formula into a program statement, you would use variables to record the radius and circumference. These variables change depending on the data. The values 2 and π, however, are constants—explicit values that never change. The value 2 is an integer constant, and the value π is a real number constant, which would be represented in a program by a floating-point approximation, such as 3.14159. Because constants are an important building block for constructing expressions, it is important to be able to write constant values for each of the basic data types.

1. Integer constants. To write an integer constant as part of a program or as input data, you simply write the digits that make up the number. If the integer is negative, you write a minus sign before the number, just as in mathematics. Commas are never used.

Thus, the value one million must be written as 1000000 and not as 1,000,000.

2. Floating-point constants. Floating-point constants in C are written with a decimal point. Thus, if 2.0 appears in a program, the number is represented internally as a floating-point value; if the programmer had written 2, this value would be an integer.

Floating-point values can also be written in a special programmer’s style of scientific notation, in which the value is represented a floating-point number multiplied by an integral power of 10. To write a number using this style, you write a floating-point number in standard notation, followed immediately by the letter E and an integer

exponent, optionally preceded by a + or sign. For example, the speed of light in meters per second is approximately

2.9979 × 108

which can be written in C as 2.9979E+8

where the E stands for the words times 10 to the power.

3. String constants. You write a string constant in C by enclosing the characters that comprise the string in double quotation marks. For example, the very first example of data used in this text was the string

“Hello, world.\n”

in the hello.c program. This string consists of the characters shown between the quotation marks, including the letters, the space, the punctuation symbols, and the special newline character. The quotation marks are not part of the string but sever only to mark its beginning and end.

Variables

A variable is a placeholder for a value and has three important attributes: a name, a value, and a type. To understand the relationship of these attributes, think of a variable as a box with a label attached to the outside. The name of the variable appears on the label and is used tell the different boxes apart. If you have three boxes (or variables), you can refer to a particular one using its name. The value of the variable corresponds to the contents of the box and put new values in as often as you like. The type of the variable indicates what kind of data values can be stored in the box. For example, if you have a box designed to hold values of type int, you cannot put values of type string into that box.

Variable names in C are constructed according to the following rules:

1. The name must start with a letter or the underscore character (_). In C, uppercase and lowercase letters appearing in a variable name are considered to be different, so the name ABC, Abc, and abc refer to three separate variables.

2. All other characters in the name must be letters, digits, or the underscore. No spaces or other special characters are permitted in names.

3. The name must not be one of the following keywords, which are names that C defines for a specific purpose:

Atuo double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

4. Variable names can be of any length, but C compilers are required to consider

only the first 31 characters as significant1. Thus, if two variable names have the same first 31 characters, subsequent differences may not be recognized by some compilers. For example, the variable name

anExtremelyLonVariableNameWith43Characters

may be treated as identical to

anExtremelyLongVariableNameWithAdifferentEnding

Because the two names are exactly the same through the first 31 characters.

As a general rule to guard against such mix-ups, it is usually best to avoid using names with more than 31 characters.

5. The variable name should make it obvious to the reader what value is being stored. Although names of friends, expletives, and the like may be legal according to the other rules, they do absolutely nothing to improve the readability of your programs.

As noted in the discussion of the add2.c program, you must explicitly specify the data type of every variable before you use it in a program. This process is known as declaring the variable. Variables are usually declared at the beginning of a function. (So far in this text, the only function in which variables have been declared is the function main, but it is legal to declare variables in any function.) The declaration itself consists of a type name, followed by a list of variables to be declared as instances of that type. For example, the add2.c program declares three variables with the line

int n1, n2, total;

The names of these variables are n1, n2, and total, all of which are of type int. Thus, using the box analogy for variables, the effect of this declaration is to create the following three boxes, with the names n1, n2, and total:

The initial value of each variable is undefined, and you should not make any assumptions about what values these boxes hold when the program begins. The variable n1 might contain 73 or any other random value; you won’t know what value is there until you put one there yourself.

If you need to declare values of a different type, you can use additional declaration statements at the beginning of the function. For example, you could declare the variable msg to be of type string by writing the declaration

string msg;

Once again, the effect of this declaration in terms of the box analogy is to create a new box with the name msg:

1 Variable names that are shared between separate program files often consider even fewer

characters to be significant. To be safe, it is best to make sure that any names that are shared between files can be distinguished by considering their first six characters.

msg

n2 total

n1

In this diagram, I have chosen a different shape for the box to emphasize that the type of the variable msg is different from that of the variables n1, n2, and total. The variable n1, for example, is of type int and can hold only integer data; the variable msg is of type string and can hold only string data. Trying to put the wrong type of data into one of these variables is the computational equivalent of attempting to put a square peg into a round hole and will be caught by the compiler as an error.