• No results found

Problem Solving Applied: Ozone Measurements 135

In document Engineering Problem Solving With C (Page 158-171)

Generating a Data File

Section 3.9 Problem Solving Applied: Ozone Measurements 135

The steps in the pseudocode are now detailed enough to convert into C:

/*––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/

/* Program chapter3_10 */

/* */

/* This program computes a linear model for a set */

/* of altitude and ozone mixing ratio values. */

#include <stdio.h>

#define FILENAME "zone1.txt"

int main(void) {

/* Declare and initialize variables. */

int count=0;

double x, y, first, last, sumx=0, sumy=0, sumx2=0, sumxy=0, denominator, m, b;

FILE *zone;

/* Open input file. */

zone = fopen(FILENAME,"r");

if (zone == NULL)

printf("Error opening input file. \n");

else {

/* While not at the end of the file, */

/* read and accumulate information. */

while ((fscanf(zone,"%lf %lf",&x,&y)) == 2) {

++count;

if (count == 1) first = x;

sumx += x;

sumy += y;

sumx2 += x*x;

sumxy += x*y;

}

last = x;

/* Compute slope and y-intercept. */

denominator = sumx*sumx - count*sumx2;

m = (sumx*sumy - count*sumxy)/denominator;

b = (sumx*sumxy - sumx2*sumy)/denominator;

/* Print summary information. */

printf("Range of altitudes in km: \n");

printf("%.2f to %.2f \n\n",first,last);

printf("Linear model: \n");

printf("ozone-mix-ratio = %.2f altitude + %.2f \n", m,b);

/* Close file. */

fclose(zone);

}

/* Exit program. */

return 0;

}

/*––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/

5. TESTING

Using the data from the hand example as the contents of the data file zone1.txt, we get the following program output:

Range of altitudes in km:

20.00 to 28.00 Linear model:

ozone-mix-ratio = 0.37 altitude + -4.60 This matches the values computed from the hand example.

These problems relate to the program developed in this section. You may need to use the fol-lowing relationship in some of the problems:

1. Add statements to the program so that it allows you to enter an altitude in kilometers.

The program should use the model to estimate the corresponding ozone mix ratio.

2. Modify the program in Problem 1 so that it checks the altitude that you enter to deter-mine whether it is appropriate for this model.

3. Modify the program in Problem 2 so that it allows you to enter the altitude in miles.

(The program should convert miles to kilometers.)

4. Modify the original program so that it also prints a linear model so that it can be used with altitudes that are in miles instead of kilometers. Assume that the data file still con-tains altitudes in kilometers.

1 km = 0.621 mi.

M O D I F Y !

M O D I F Y !

C Statement Summary 137 In this chapter, we covered the use of conditions and ifstatements to select the proper state-ments to be executed. We also presented techniques for repeating sets of statestate-ments in loops.

These loops can be implemented as whileloops or forloops. Selection and repetition structures are used in most programs. In addition, we included the statements necessary to read information from a data file so that we could use the information in the program. We also presented the statements to generate a data file from a program. Data files are common-ly used in solving engineering problems; therefore, this concept was presented earcommon-ly in the text so that we could use it in many of the later problem solutions. Finally, we covered the concept of generating a linear model for a set of data points and included the equations for determining the best fit in terms of least squares.

KEY TERMS

temp>100 ? printf("Caution \n"): printf("Normal \n");

if/elsestatement:

if (d <= 30)

velocity = 4.25 + 0.00175*d*d;

else

velocity = 0.65 + 0.12*d - 0.0025*d*d;

3

switchstatement:

switch (op_code) {

case 'n': case 'r':

printf("Normal operating range \n");

break;

case 'm':

printf("Maintenance needed \n");

break;

default:

printf("Error in code value \n");

break;

}

whileloop:

while (degrees <= 360) {

radians = degrees*PI/180;

printf("%6.0f %9.6f \n",degrees,radians);

degrees += 10;

}

do/whileloop:

do {

radians = degrees*PI/180;

printf("%6.0f %9.6f \n",degrees,radians);

degrees += 10;

} while (degrees <= 360);

forloop:

for (degrees=0; degrees<=360; degrees+=10) {

radians = degrees*PI/180;

printf("%6.0f %9.6f \n",degrees,radians);

}

breakstatement:

break;

continuestatement:

continue;

File open function:

sensor = fopen("sensor1.txt","r");

waves = fopen(FILENAME,"w");

Debugging Notes 139 File input function:

fscanf(sensor,"%lf %lf",&t,&motion);

File output function:

fprintf(waves,"%.2f %.2f %.2f %.2f \n",t,w1,w2,sum);

File close function:

fclose(sensor);

NOTES

1. Use spaces around the relational operator in a logical expression in a simple condition;

use spaces around the logical operator and not around the relational operators in a com-plicated condition.

2. Indent the statements within a compound statement or inside a loop. If loops or compound statements are nested, indent each nested set of statements from the previous statement.

3. Even when they are not required, use braces to clearly identify the structure of a compli-cated statement.

4. Use the default case within the switchstatement to emphasize the action to take when none of the case labels matches the controlling expression.

5. Put each brace on a line by itself so that the body of the loop is easily identified.

6. Define file names with preprocessor directives so that they can easily be changed.

DEBUGGING NOTES

1. When you discover and correct an error in a program, start the testing step over again. In particular, rerun the program with all the test data sets.

2. Be sure to use the relational operator ==instead of =in a condition for equality.

3. Put the braces surrounding a block of statements on lines by themselves; this will help you avoid omitting them.

4. Do not use the equality operator with floating-point values; instead, test for values “close to” a desired value.

5. Recompile your program frequently when correcting syntax errors; correcting one error may remove many error messages.

6. When debugging loops, use the printfstatement to give memory snapshots of the val-ues of key variables.

7. Be sure you know the special characters needed to abort the execution of a program on your system if it goes into an infinite loop. It is easier than you think to generate an infinite loop.

8. When debugging a program that reads data from a data file, print the values as soon as they are read. This will help you check for errors in reading the information.

9. When debugging a program that reads a data file, be sure that your program can access the directory that contains the data file.

10. To avoid problems with operating systems that are not case sensitive, use file names with lowercase letters.

3

PROBLEMS

S H O R

S H O RTT A N S W E R P RA N S W E R P RO B L E M SO B L E M S True–False Problems

Indicate whether the following statements are true (T) or false (F):

1. If a condition’s value is zero, then the condition is evaluated as false. T F 2. If the condition’s value is neither zero nor 1, then it is an invalid condition. T F 3. The expression a == 2is used to determine if the value of ais equal

to 2, and the expression a = 2assigns the value of 2 to the variable a. T F 4. The logical operators &&and||have the same precedence level. T F 5. The reserved word elseis always associated with the closest if

statement unless braces are used to define blocks of statements. T F 6. To debug a loop, we can use printfstatements in the loop to

provide memory snapshots of variables. T F

Syntax Problems

Identify any syntax errors in the following statements (assume that the variables have all been defined as integers):

7. for (b=1, b=<25, b++) 8. while (k=1)

9. switch (sqrt(x)) {

case 1:

printf("Too low. \n");

break;

case 2:

printf("Correct range. \n");

break;

case 3:

printf("Too high. \n");

break;

}

Multiple Choice Problems

Circle the letter for the best answer to complete each statement or for the correct answer to each question.

10. Consider the following statement:

int i=100, j=0;

Which of the following statements are true?

(a) i<3 (b) !(j<1)

(c) (i>0) || (j>50) (d) (j<i) && (i<=10)

Problems 141 11. If a1is true and a2is false, then which of the following expressions are true?

(a) a1 && a2 (b) a1 || a2 (c) !(a1 || a2) (d) !a1 && a2

12. Which of the following are unary operators?

(a) ! (b) ||

(c) &&

13. The expression (!((3-4%3) < 5 && (6/4 >3))) is (a) true.

(b) false.

(c) invalid.

(d) none of the above.

Problems 14–16 refer to the following statements:

int sum=0, count;

...

for (count=0; count<=4; count++) sum += count;

printf("sum= %i \n",sum);

14. What would you find on the screen?

(a) sum = 1 (b) sum = 6

(c) sum = 10 (d) an error message 15. What is the value of countafter execution of the forloop?

(a) 0 (b) 4

(c) 5 (d) an unpredictable integer

16. How many times are the statements inside the loop executed?

(a) 0 (b) 4

(c) 5 (d) 6

Memory Snapshot Problems

Give the corresponding snapshots of memory after the following set of statements is executed.

17. int a = 750;

...

if (a>0)

if (a >= 1000) a = 0;

else

if (a < 500) a *= 2;

else

a *= 10;

else a += 3;

3

P RP RO G R A M M I N G P RO G R A M M I N G P RO B L E M SO B L E M S

Unit Conversions. The following problems generate tables of unit conversions. Include a table heading and column headings for the tables. Choose the number of decimal places based on the values to be printed.

18. Generate a table of conversions from radians to degrees. Start the radian column at 0.0, and increment by until the radian amount is

19. Generate a table of conversions from degrees to radians. The first line should contain the value for 0° and the last line should contain the value for 360°. Allow the user to enter the increment to use between lines in the table.

20. Generate a table of conversions from inches to centimeters. Start the inches column at 0.0 and increment by 0.5 in. The last line should contain the value 20.0 in. (Recall that

)

21. Generate a table of conversions from miles per hour to feet per second. Start the mph col-umn at 0, and increment by 5 mph. The last line should contain the value 65 mph. (Recall that )

22. Generate a table of conversions from feet per second to miles per hour. Start the ft/s col-umn at 0 and increment by 5 ft/s. The last line should contain the value 100 ft/s. (Recall that )

Currency Conversions. The following problems generate tables of currency conversions.

Use title and column headings. Assume the following conversion rates:

(£) (UK)

23. Generate a table of conversions from Euros to dollars. Start the Euros column at 5 Euros and increment by 5 Euros. Print 25 lines in the table.

24. Generate a table of conversions from pounds (£) to dollars. Start the pounds column at 1 £ and increment by 2 £. Print 30 lines in the table.

25. Generate a table of conversions from yen to pounds. Start the yen column at 100 Y and print 25 lines, with the final line containing the value 10,000 Y.

26. Generate a table of conversions from dollars to Euros, yen, and pounds. Start the column with $1 and increment by $1. Print 50 lines in the table.

1 dollar 1$2 = 0.632293 pounds 1 yen 1Y2 = $0.013005

1 dollar 1$2 = 0.737938 Euro 1Europe2 1 mi = 5280 ft.

1 mi = 5280 ft.

1 in = 2.54 cm.

p/10, 2p.

Problems 143 Temperature Conversions. The following problems generate temperature-conversion ta-bles. Use the following equations that give relationships between temperatures in degrees Fahrenheit degrees Celsius degrees Kelvin and degrees Rankin

27. Write a program to generate a table of conversions from Fahrenheit to Celsius for values from 0°F to 100°F. Print a line in the table for each 5° change. Use a whileloop in your solution.

28. Write a program to generate a table of conversions from Fahrenheit to Kelvin for values from 0°F to 200°F. Allow the user to enter the increment in degrees Fahrenheit between lines. Use a do whileloop in your solution.

29. Write a program to generate a table of conversions from Celsius to Rankin. Allow the user to enter the starting temperature and increment between lines. Print 25 lines in the table. Use a forloop in your solution.

Sounding Rocket Trajectory. Sounding rockets are used to probe different levels of the at-mosphere to collect information (such as that used to monitor the levels of ozone in the atmos-phere). In addition to carrying the scientific package for collecting data in the upper atmosphere, the rocket also carries a telemetry system to transmit scientific data to a receiver at the launch site. Performance measurements on the rocket itself are also transmitted, so they can be monitored by range safety personnel and later analyzed by engineers. These performance data include altitude, velocity, and acceleration data. Assume that this information is stored in a file and that each line contains four values—time, altitude, velocity, and acceleration. As-sume that the units are seconds, meters, meters/second, and respectively.

30. Assume that the file rocket1.txtcontains an initial line that contains the number of actual data lines that follows. Write a program that reads these data and determines the time at which the rocket begins falling back to earth. (Hint: Determine the time at which the altitude begins to decrease.)

31. The number of stages in the rocket can be determined by the number of times that the ve-locity increases to some peak and then begins decreasing. Write a program that reads these data and determines the number of stages on the rocket. Use the data file rocket2.txt. It contains a trailer line with the value for all four values.

32. Modify the program in Problem 31 so that it prints the times that correspond to the firing of each stage. Assume that the firing corresponds to the point at which the velocity begins to increase.

33. After each stage of the rocket is fired, the acceleration will initially increase and then de-crease to which is the downward acceleration due to gravity. Find the time pe-riods of the rocket flight during which the acceleration is due only to gravity. Allow the acceleration to range up to 65% of the theoretical value for these time periods. Use the data file rocket3.txt, which does not contain a header line or a trailer line.

-9.8 m/s2,

Suture Packaging. Sutures are strands or fibers used to sew living tissue together after an in-jury or an operation. Packages of sutures must be sealed carefully before they are shipped to hospitals so that contaminants cannot enter the packages. The object that seals the package is referred to as a sealing die. Generally, sealing dies are heated with an electric heater. For the sealing process to be a success, the sealing die is maintained at an established temperature and must contact the package with a predetermined pressure for an established time period. The time period in which the sealing die contacts the package is called the dwell time. Assume that the acceptable range of parameters for an acceptable seal are the following:

34. A data file named suture1.txtcontains information on batches of sutures that have been rejected during a one-week period. Each line in the data file contains the batch number, temperature, pressure, and dwell time for a rejected batch. The quality control engineer must analyze this information, and needs a report that computes the percent of the batch-es rejected due to temperature, the percent rejected due to prbatch-essure, and the percent re-jected due to dwell time. It is possible that a specific batch may have been rere-jected for more than one reason, and it should be counted in all applicable totals. Write a program to compute and print these three percentages.

35. Modify the program developed in Problem 34 such that it also prints the number of batches in each rejection category and the total number of batches rejected. (Remember that a rejected batch should appear only once in the total, but could appear in more that one rejection category.)

36. Write a program to read the data file suture1.txtand make sure that the information relates only to batches that should have been rejected. If any batch should not be in the data file, print an appropriate message with the batch information.

Timber Regrowth. One problem in timber management is to determine how much of an area to leave uncut so that the harvested area is reforested in a certain period of time. It is as-sumed that reforestation takes place at a known rate per year, depending on climate and soil conditions. A reforestation equation expresses this growth as a function of the amount of tim-ber standing and the reforestation rate. For example, if 100 acres are left standing after har-vesting and the reforestation rate is 0.05, then or 105 acres, are forested at the end of the first year. At the end of the second year, the number of acres forested is

or 110.25 acres.

37. Assume that the area has a total of 14,000 acres, with 2500 acres uncut and a reforesta-tion rate of 0.02. Print a table showing the number of acres forested at the end of each year, for a total of 20 years.

38. Modify the program developed in Problem 37 so that the user can enter the number of years to be used for the table.

105 + (0.05

#

105),

100 + (0.05

#

100), Temperature: 150 – 170°C, Pressure: 60 – 70 psi, Dwell time: 2 – 2.5 s.

Problems 145 39. Modify the program developed in Problem 37 so that the user can enter a number of acres and the program will determine how many years are required for the number of acres to be completely reforested.

Critical Path Analysis. A critical path analysis is a technique used to determine the time schedule for a project. This information is important in the planning stages before a project is begun, and it is also useful to evaluate the progress of a project that is partially completed.

One method for this analysis starts by dividing a project into sequential events and then di-viding each event into various tasks. Although one event must be completed before the next one is started, various tasks within an event can occur simultaneously. The time it takes to complete an event, therefore, depends on the number of days required to finish its longest task. Similarly, the total time it takes to finish a project is the sum of time it takes to finish each event.

Assume that the critical path information for a major construction project has been stored in a data file. Each line of the data file contains an event number, a task number, and the number of days required to complete the task. The data have been stored such that all the task data for the first event are followed by all the task data for the second event, and so on. A typ-ical set of data is shown in the following table.

Event Task Number of Days

1 15 3

1 27 6

1 36 4

2 15 5

3 18 4

3 26 1

4 15 2

4 26 7

4 27 7

5 16 4

40. Write a program to read the critical path information and to print a project completion timetable that lists each event number, the maximum number of days for a task within the event, and the total number of days for the project completion.

41. Write a program to read the critical path information and to print a report that lists the event number and task number for all tasks requiring more than five days.

42. Write a program to read the critical path information and to print a report that lists the number of each event and a count of the number of tasks within the event.

Weather Balloons. Weather balloons are used to gather temperature and pressure data at var-ious altitudes in the atmosphere. The balloon rises because the density of the helium inside the balloon is less than the density of the surrounding air outside the balloon. As the balloon rises, the surrounding air becomes less dense, and thus the balloon’s ascent slows until it

3

reaches a point of equilibrium. During the day, sunlight warms the helium trapped inside the balloon, which causes the helium to expand and become less dense; thus, the balloon will rise higher. During the night, however, the helium in the balloon cools and becomes more dense;

thus, the balloon will descend to a lower altitude. The next day, the sun heats the helium again and the balloon rises. Over time, this process generates a set of altitude measurements that can be approximated with a polynomial equation. Assume that the following polynomial repre-sents the altitude or height in meters during the first 48 hours following the launch of a weath-er balloon:

where the units of t are hours. The corresponding polynomial model for the velocity in meters per hour of the weather balloon is

Figure 3.16 contains a plot of the altitude and velocity of the balloon for a period of 48 hours.

From the plots, we can see the periods during which the balloon rises or falls.

v1t2 = -0.48t3 + 36t2 - 760t + 4100.

alt1t2 = –0.12t4 + 12t3 - 380t2 + 4100t + 220,

0 5 10 15 20 25 30 35 40 45 50

1

0.5 0 0.5 1 1.5

Time, hr

Velocity, meters/sec

Balloon Velocity

0 5 10 15 20 25 30 35 40 45 50

0 0.5 1 1.5

2 104

Time, hr

Altitude, meters

Balloon Altitude

Figure 3.16 Velocity and altitude data for a weather balloon.

Problems 147 43. Write a program that will print a table of the altitude and the velocity for this weather balloon using units of meters and meters per second. Let the user enter the start time, the

Problems 147 43. Write a program that will print a table of the altitude and the velocity for this weather balloon using units of meters and meters per second. Let the user enter the start time, the

In document Engineering Problem Solving With C (Page 158-171)