03 0672326965 CH03 10/19/04 1:53 PM Page 49 CHAPTER 3 DATA AND C You will learn about the following in this chapter: • Keywords: • The distinctions between integer int, short, long, unsigned, char, types and floating-point types float, double, _Bool, _Complex, • Writing constants and declaring _Imaginary variables of those types • Operator: • How to use the printf() and sizeof scanf() functions to read and • Function: write values of different types scanf() • The basic data types that C uses rograms work with data. You feed numbers, letters, and words to the computer, and you expect it to do something with the data. For example, you might want the com- puter to calculate an interest payment or display a sorted list of vintners. In this chap- ter,P you do more than just read about data; you practice manipulating data, which is much more fun. This chapter explores the two great families of data types: integer and floating point. C offers several varieties of these types. This chapter tells you what the types are, how to declare them, and how and when to use them. Also, you discover the differences between constants and variables, and as a bonus, your first interactive program is coming up shortly. A Sample Program Once again, you begin with a sample program. As before, you’ll find some unfamiliar wrinkles that we’ll soon iron out for you. The program’s general intent should be clear, so try compiling and running the source code shown in Listing 3.1. To save time, you can omit typing the com- ments. 03 0672326965 CH03 10/19/04 1:53 PM Page 50 50 C PRIMER PLUS LISTING 3.1 The rhodium.c Program /* rhodium.c -- your weight in rhodium */ #include <stdio.h> int main(void) { float weight; /* user weight */ float value; /* rhodium equivalent */ printf(“Are you worth your weight in rhodium?\n”); printf(“Let’s check it out.\n”); printf(“Please enter your weight in pounds: “); /* get input from the user */ scanf(“%f”, &weight); /* assume rhodium is $770 per ounce */ /* 14.5833 converts pounds avd. to ounces troy */ value = 770.0 * weight * 14.5833; printf(“Your weight in rhodium is worth $%.2f.\n”, value); printf(“You are easily worth that! If rhodium prices drop,\n”); printf(“eat more to maintain your value.\n”); return 0; } Errors and Warnings If you type this program incorrectly and, say, omit a semicolon, the compiler gives you a syntax error message. Even if you type it correctly, however, the compiler may give you a warning similar to “Warning—conversion from ‘double’ to ‘float,’ possible loss of data.” An error message means you did something wrong and prevents the program from being compiled. A warning, however, means you’ve done something that is valid code but possibly is not what you meant to do. A warning does not stop compilation. This particular warning pertains to how C handles values such as 770.0. It’s not a problem for this example, and the chapter explains the warning later. When you type this program, you might want to change the 770.0 to the current price of the precious metal rhodium. Don’t, however, fiddle with the 14.5833, which represents the num- ber of ounces in a pound. (That’s ounces troy, used for precious metals, and pounds avoirdu- pois, used for people—precious and otherwise.) Note that “entering” your weight means to type your weight and then press the Enter or Return key. (Don’t just type your weight and wait.) Pressing Enter informs the computer that you have finished typing your response. The program expects you to enter a number, such as 150, not words, such as too much. Entering letters rather than digits causes problems that require an if 03 0672326965 CH03 10/19/04 1:53 PM Page 51 Chapter 3 • DATA AND C 51 statement (Chapter 7, “C Control Statements: Branching and Jumps”) to defeat, so please be polite and enter a number. Here is some sample output: Are you worth your weight in rhodium? Let’s check it out. Please enter your weight in pounds: 150 Your weight in rhodium is worth $1684371.12. You are easily worth that! If rhodium prices drop, eat more to maintain your value. What’s New in This Program? There are several new elements of C in this program: • Notice that the code uses a new kind of variable declaration. The previous examples just used an integer variable type (int), but this one adds a floating-point variable type (float) so that you can handle a wider variety of data. The float type can hold num- bers with decimal points. • The program demonstrates some new ways of writing constants. You now have numbers with decimal points. • To print this new kind of variable, use the %f specifier in the printf() code to handle a floating-point value. Use the .2 modifier to the %f specifier to fine-tune the appearance of the output so that it displays two places to the right of the decimal. • To provide keyboard input to the program, use the scanf() function. The %f instructs scanf() to read a floating-point number from the keyboard, and the &weight tells scanf() to assign the input value to the variable named weight. The scanf() function uses the & notation to indicate where it can find the weight variable. The next chapter discusses & further; meanwhile, trust us that you need it here. • Perhaps the most outstanding new feature is that this program is interactive. The com- puter asks you for information and then uses the number you enter. An interactive pro- gram is more interesting to use than the noninteractive types. More important, the interactive approach makes programs more flexible. For example, the sample program can be used for any reasonable weight, not just for 150 pounds. You don’t have to rewrite the program every time you want to try it on a new person. The scanf() and printf() functions make this interactivity possible. The scanf() function reads data from the keyboard and delivers that data to the program, and printf() reads data from a program and delivers that data to your screen. Together, these two functions enable you to establish a two-way communication with your computer (see Figure 3.1), and that makes using a computer much more fun. This chapter explains the first two items in this list of new features: variables and constants of various data types. Chapter 4, “Character Strings and Formatted Input/Output,” covers the last three items, but this chapter will continue to make limited use of scanf() and printf(). 03 0672326965 CH03 10/19/04 1:53 PM Page 52 52 C PRIMER PLUS FIGURE 3.1 Body The scanf() and printf() functions at /*rhodium.c*/ work. • • int main(void) { • • • scanf("-----) getting keyboard input • • • printf("Are you--) displaying program output Are you printf(-----) --- • • return 0; } Data Variables and Constants A computer, under the guidance of a program, can do many things. It can add numbers, sort names, command the obedience of a speaker or video screen, calculate cometary orbits, pre- pare a mailing list, dial phone numbers, draw stick figures, draw conclusions, or anything else your imagination can create. To do these tasks, the program needs to work with data, the numbers and characters that bear the information you use. Some types of data are preset before a program is used and keep their values unchanged throughout the life of the program. These are constants. Other types of data may change or be assigned values as the program runs; these are variables. In the sample program, weight is a variable and 14.5833 is a con- stant. What about 770.0? True, the price of rhodium isn’t a constant in real life, but this pro- gram treats it as a constant. The difference between a variable and a constant is that a variable can have its value assigned or changed while the program is running, and a constant can’t. Data: Data-Type Keywords Beyond the distinction between variable and constant is the distinction between different types of data. Some types of data are numbers. Some are letters or, more generally, characters. The computer needs a way to identify and use these different kinds. C does this by recognizing sev- eral fundamental data types. If a datum is a constant, the compiler can usually tell its type just by the way it looks: 42 is an integer, and 42.100 is floating point. A variable, however, needs to have its type announced in a declaration statement. You’ll learn the details of declaring vari- ables as you move along. First, though, take a look at the fundamental types recognized by C. K&R C recognized seven keywords relating to types. The C90 standard added two to the list. The C99 standard adds yet another three (see Table 3.1). 03 0672326965 CH03 10/19/04 1:53 PM Page 53 Chapter 3 • DATA AND C 53 TABLE 3.1 C Data Keywords Original K&R Keywords C90 Keywords C99 Keywords int signed _Bool long void _Complex short _Imaginary unsigned char float double The int keyword provides the basic class of integers used in C. The next three keywords (long, short, and unsigned) and the ANSI addition signed are used to provide variations of the basic type. Next, the char keyword designates the type used for letters of the alphabet and for other characters, such as #, $, %, and *. The char type also can be used to represent small integers. Next, float, double, and the combination long double are used to represent num- bers with decimal points.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages40 Page
-
File Size-