• 沒有找到結果。

The #define mechanism

The best tool available in C for centralizing editing changes is the #define construct. In its simplest form, #define has the following paradigmatic form:

#define symbol value

In this paradigm, symbol represents a name that follows the same rules used for variables and value represents a C constant. Whenever the symbol appears anywhere in the program after #define is introduced, the specified value is substituted in place of the symbol. For example, if you put the line

#define bouncedCheckFee 10.00

at the beginning of the checkbook program, you could then rewrite the if statement as follows to take advantage of the definition:

if (entry < 0 && balance <0){

printf(“This check bounces. $%.2f fee deducted.\n”, bouncedCheckFee);

balance -= BouncedCheckFee;

}

To change the bounced-check fee in the future, the programmer who inherits this program would only have to change the #define statement at the top of the program.

The final version of the checkbook-balancing program, which includes both the change in the printf format specification and the definition of the BouncedCheckFee constant, is shown in Figure 3-7. Note that the program also includes additional comments to help new programmers understand how to change BouncdCheckFee to some different value.

FIGURE 3-7

balance4.c(final version) /*

* File: balance4.c

* ---

* This file contains the version of a program to

* balance a checkbook.

*/

#include <stdio.h>

#include “genlib.h”

#include “simpio.h”

/*

* Constant: BouncedCheckFee

* ---

* To change the charge assessed for bounced checks, change

* the definition of this constant. The constant must be a

* floating-point value (i.e., must contain a decimal point).

*/

#define BouncedCheckFee 10.00

/* Main program */

main() {

double entry, balance;

printf(“This program helps you balance your checkbook.\n”);

printf(“Enter each check and deposit during the month.\n”);

printf(“To indicate a check, use a minus sign.\n”);

printf(“Signal the end of the month with a 0 value.\n”);

printf(“Enter the initial balance: \n”);

balance = GetReal();

while (TURE) {

printf(“ Enter check (-) or deposit: “);

entry = GetReal();

if (entry == 0) break;

balance += entry;

if (balance < 0 && entry < 0) {

printf(“This check bounces. $%.2f fee deducted.\n”,BouncedCheckFee);

balance -= BouncedCheckFee;

}

printf(“Current balance = %.2f\n”, balance);

}

printf(“Final balance = %.2f\n”, balance);

}

Using #define to set values of constant that are likely to change is an important part of good software engineering. You will see many additional examples of this technique throughout the text.

SUMMARY

In Chapter 2, you learned how to write simple programs that accept input data, calculate results, and generate output. Chapter 3 has sought to extend your knowledge by introducing the concept of control statements. By using control statements, you can make your programs solve much more sophisticated problems, such s those that involve testing to see whether a condition holds or those that require repetition of certain operation.

This chapter encourages you to approach control statements by thinking about the kinds of problems they can solve. Each statement is a tool appropriate to a particular situation, and you have seen how to apply particular tools through the use of simple idioms and paradigms. Chapter 4 looks at control statements in more detail.

Beyond becoming familiar with control statements, you also had the opportunity—primarily through the evolution of the balance.c example—to discover that writing programs to solve problems is not as easy as it might appear. Particularly if you think too quickly about your modifications to a program or fail to test programs thoroughly, it is easy to introduce subtle bugs into your programs that keep them from working as you intend. To some extent, such bugs are an unavoidable part of the programming process, but you can save yourself considerable time and aggravation by using good programming discipline. To help you develop that discipline, this chapter includes several useful guidelines and conventions to improve you programming skills.

Important points about programming introduced in this chapter are:

Common operations within a program can be represented as programming idioms,

which permit you to learn one simple pattern that is applicable to a variety of programming problems.

C defines several shorthand assignment operators that make it easier for you to specify certain common operations.

Strategies that work for two or three data values are often not appropriate as the scale of the problem grows.

The for statement can be used to repeat a set of statements a specified number of times.

When used in the particular idiomatic form given in this chapter, the while statement can be used to repeat a set of statements until a designated sentinel value is entered.

The if statement is used to specify that a particular set of statements should be executed only If a certain condition applies. The condition itself is ordinarily expressed by using relational operators to compare two data values.

Seemingly innocuous changes can introduce serious bugs. You should always be suspicious of your program and test them as thoroughly as you can.

The printf function provides considerable control over output formatting.

Programs should be written so that they can be understood easily by other programmers. It is important for you to write your programs with future readers in mind.

REVIEW QUESTIONS

1. Explain the concept of a programming idiom. What role do such idioms play in the process of learning to program?

2. What is the idiom that corresponds to the English command ―request an integer value from the user and store it in a variable"?

3. What idiom would you use to multiply the value of the variable cellCount by 2?

4. What is the most common way in c to write a statement that has the same effect as x = x+ 1;

5. What idiom would you use to repeat a set of commands 15 times?

6. Define the following terms: loop, control line, cycle, body, and index variable.

7. What for control line would you use to count from 15 to 25?

8. In the add10.c program, the statement total = 0;

appears before the for lop. Why is this statement important? On the other hand, why is it not necessary to include the following statement as well?

value = 0;

Explain how the different use of these variables makes it necessary to initialize total but not value.

9. What is a sentinel? What considerations are involved in choosing a sentinel value for a particular application?

10. What is the idiom presented in this chapter for repeating an operation on a list of input values until a sentinel value appears?

11. What statement is used in this chapter to specify conditional execution, and what are its two forms?

12. What are the six relational operators that exist in C, and what are the corresponding mathematical symbols?

13. Why is it important to test programs thoroughly, even after making simple, seemingly innocuous changes?

14. In the balance.c program, what is the reason for using the format specification $.2f in the printf calls?

15. How would you write a printf statement to display the string value stored in the variable name, so that the resulting output was left justified in a 20-character field? How would you ensure that names longer than 20 characters would not affect the alignment of other items in a table?

16. How would you write a printf statement to display the floating-point value stored in the variable distance so that exactly three digits appear to the right of the decimal point?

17. What factors should you consider when choosing variable names for your programs?

18. What is the advantage of the #define construct in terms of program maintenance?

19. How would you use #define to introduce a constant name pi with the value 3.14159?

20. In the balance.4c program (Figure 3-7), the comment associated with the definition of BouncedCheckfee indicates that the constant value must be a floating-point number. What statement in the program would fail to operate correctly if BouncedCheckfee were defined as an integer in violation of this rule? How could you change the program to eliminate this restriction?

21. As a programmer, you must be able to put yourself in the position of a user. From this perspective, consider the balance.c program presented in this chapter. Is the program easy to use? Does it provide the capabilities you want? What changes would you make in the behavior of the program?

22. In any form of writing, it is important to consider your audience. If your audience misses the point, the text has not accomplished its purpose. In writing a program, who is your most important audience?

PROGRAMMING EXERCISES

1. As noted I the section on ―The read-until-sentinel idiom,‖ one strategy for generalizing the add10.c program is to allow the user to enter the number of values to be added when the program is run. As outlined in the text, make the modifications necessary to change the addd10.c program so that it reads in the number of values first, followed by the actual numbers to be added.

2. Write a program that displays the message Hello, world.

10 times on separate lines.

3. Using the Gertrude Stein ―a rose is a rose is a rose‖ example as an model, write the for loop that displays the repeated parts of Macbeth’s lament

4. Modify the add10.c program so that instead of adding integers, it adds 10 floating-point numbers.

5. Write a program that prints out the squares of the numbers from 1 to 10, using the format shown in the following sample run:

Design your program so that the limits 1 and 10 are easy to change.

6. According to legend, the German mathematician Karl Friedrich Gauss (1777-a855) began to show his mathematical talent at a very early age. When he was in elementary school, Gauss was asked by his teacher to compute the sum of the numbers between 1 and 100. Gauss is said to have given the answer instantly: 5050. Write a program that computes the answer to the question Gauss’s teacher posed.

7. Write a program that reads in five integers from the user and then displays their average, as illustrated by the following sample run:

Note that even though all the input values are integers, the average may have a decimal fraction. Also, remember to design your program so that it is easy to change the number of input values to some number other than five.

8. Modify the program you wrote in exercise 7 so that the program begins by asking the user for the number of values, like this:

Tomorrow and tomorrow and tomorrow.

1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 6 squared is 36 7 squared is 49 8 squared is 64 9 squared is 81 10 squared is 100

This program averages a list of 5 integers.

? 95 

? 100 

? 89 

? 91 

? 97 

The average is 94.4

This program averages a list of 5 integers.

How many values are there in the list> 5 

? 95 

? 100 

? 89 

? 91 

? 97 

The average is 94.4

9. Using the addlist.c example as a model, write a program that reads in a list of integers until the user enters the value –1 as a sentinel. At that point, the program should display the average of the values entered so far. Your program should be able to duplicate the following sample run:

Writing this program requires more thought than writing the addlist.c program in the text and is a good test of your problem solving abilities.

10. The section on ―The repeat-N-times idiom‖ uses the following code to display one of Gertrude Stein’s familiar lines:

for ( = 0; i < 2; i++) { printf(“a rose is “);

}

printf(“a rose.\n”);

Rewrite this program so that the word rose appears only once. Your new program should generate exactly the same output as the original, including the period and the newline character.

11. In the program you wrote for exercise 5, the output was not formatted into columns, which makes the result more difficult to read. Change the program so that it prints a tabular version of both the squares and cubes of the numbers from 1 to 10, as follows:

12. Suppose you are writing a program to display a table of vote totals for candidates at a convention. When your program is ready to display the output data, the name of the candidate is stored in the string variable candidate, and the votes for that candidate are stored in the integer variable votes. How would your write a printf statement to display the name and vote count so that the names line up on the left and the numbers line up on the right, as illustrated by the following table, which shows the delegate tallies

This program averages a list of 5 integers.

Enter –1 to signal the end of the list.

? 95 

? 100 

? 89 

? 91 

? 97 

? –1 

The average is 94.4

Number Square Cube

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 454

8 64 512

9 81 729

10 100 1000

from the Democratic Party convention of 1992:

In writing this printf statement, display the name of each candidate in a 15-character field; if the name is longer than that, only the first 15 characters should appear. You may assume that there are fewer than 10,00 delegates at the convention and therefore that the number of votes never requires more than four digits to represent.

Remember that you need not write a program to generate the entire table—just the one printf statement. Even so, try to think of a way to test your printf statement to be sure it works in the desired way.

13. In exercise 4 in Chapter 2, you wrote a program to calculate compound interest over two years. Rewrite the program so that it displays the accumulated balance after each of N years, where N is a number entered by the user.

14. Write a program that reads in a list of integers from the user until the user enters the value 0 as a sentinel. When the sentinel appears, your program should display the largest value in the list, as illustrated in the following sample run:

Think about the problem before you start to write the program. What strategy do you plan to use?

Figuring out how to find the largest number in a list is by far the most conceptually important exercise in this chapter. Once you understand how to solve the fundamental problem—not the problem of how to write the necessary statements in C but rather of how to design the algorithmic strategy—you are ready to go on and learn more about details of programming.

Clinton 3372

Brown 596

Tsongas 209

Other 74

This program finds the largest integer in a list.

Enter 0 to signal the end of the list.

? 17 

? 42 

? 11 

? 19 

? 35 

? 0 

The largest value is 42

Chapter 4 Statement Forms