Computer Foundation of Postgraduate Examination: Construction algorithm and gradual improvement from top to bottom: Case Study 2

Source: Internet
Author: User
Tags repetition terminates truncated

Construction algorithm and gradual improvement from top to bottom: Case Study 2 (tag control repetition)

The following is a generalization of the average grade problem in the class, considering the following questions:

Develop a program that calculates the average class score, processing any number of scores at each program run.

In the first class average grade example, the number of scores (10) was pre-provisioned. In this case, you do not know how many scores to enter, the program to deal with any number of scores. How does the program determine when to stop entering scores? When does the average class score be calculated and printed?

One approach is to use a special value as the tag value (Sentinelvalue), also known as the Signal value (signalvalue), the dummy value (dummy value), or the flag value (flag values), indicating the end of the data input ("End of data entry") The user enters the score until all legal results are entered. The user then enters a tag value indicating that the last score has been entered. Tag control repetition (sentinel-controlled repetition) is also known as indeterminate repetition (indefinite repetition) because the number of repetitions cannot be known beforehand before the loop is executed.

Obviously, the tag value cannot be confused with an acceptable input value. Since test scores are usually non-negative integers, you can use 1 as the marker value. In this way, the average class program can handle the flow of 95, 96, 75, 74, 89 and-L. The program calculates and prints the average class score for grades 95, 96, 75, 74, and 89 (excluding-1, because it is a tagged value).

Common Programming Error 2.8

Confusing a selected tag value with an acceptable input value can cause a logic error.

We use top-down improvement (top-down,stepwise

Refinement) method to develop a program that calculates the average grade of the class, which is an important way to develop a structured program. We first generate the upper pseudo-code representation:

  Determine  the  class  avcraqe for the  quiz

The upper pseudo-code is just a statement that represents the overall function of the program. Such The upper layer equals the complete expression of the program. But the upper layer usually does not provide enough detail to write a C + + program. So begin to refine the process. We break up the upper pseudo-code into a series of small tasks, listed in the order in which they need to be done. This result is the following first step Perfect (first,refinement):

Initialize variables    Input,sum,and count the quiz grades    Calculate and print the class average

Only the sequential structure is used here, and all the steps are executed sequentially.

Software Engineering Perspective 2.4

The upper pseudo-code and every step perfect are the complete definition of the algorithm, but the degree of detail is different.

Software Engineering Perspective 2.5

Many programs can be logically divided into three stages: the initial phase of the program variable initialization, processing stage input data values and corresponding adjustment program variables, the end stage to calculate and print the final result.

The above "Software engineering perspective" is usually the first step to complete the top-down process of all work. To complete the next step (that is, the second perfect, second

Refinement), we want to specify a specific variable, to get the number of dynamic and computer processing of the number of values, with a variable to receive each input performance value, a variable to save the calculated average. The following pseudo-code statements:

      Initialize variables

Can be refined into:

Initialize Total to zero    Initialize counter to zero

Note that only the total and counter variables are initialized and reused, and the average and grade variables (averaging and user input, respectively) do not need to be initialized. Because their values are redefined at the time of calculation or input.

The following pseudo-code statements:

Input, Sum, and count the quiz grades

Each score needs to be entered consecutively with a repeating structure (that is, loops). Because we don't know how many results to deal with in advance, we use markers to control repetition. Users enter their legal results one at a time. After entering the last legitimate result, the user loses the tag value. The program tests whether it is a tagged value after each score entry. If the user enters a tagged value, the order loop terminates. The second step of the above pseudo-code statement is perfected as follows:

   Input the first grade (possibly the Sentinel) while the user have not as    yet entered the Sentinel   Add this grade in To the running total Add one to the    grade counter    Input the next grade (possibly the Sentinel)

Note that in this pseudo-code, we do not use curly braces in the while struct, except that the statements are indented under the while to indicate that they belong to while. Pseudo-code is only an informal program development aid tool.

The following pseudo-code statements can be perfected as follows:

If the counter is not equal to zero Set the average to the total divided by the     counter     Print the average    else      Print "No grades were entered"

Note that we are here to test the likelihood of a divisor of 0, which is a fatal logic error that, if not found, causes the program to fail (often referred to as an explosion or crash). Figure 2.8 shows the complete pseudo-code statement for the second step of the class's average performance problem.

Common Programming Error 2.9

A divisor of 0 is a fatal logic error.

Programming Tips 2.9

To divide, test the likelihood of a divisor of 0 and handle it appropriately in the program (such as printing an error message). Rather than let a fatal logic error occur.

The pseudo-code in Figure 2.6 and Figure 2.8 Adds a few blank lines to make the pseudo-code easier to read. Empty lines are divided into different stages of the program.

Figure 2.8 shows the pseudo-code algorithm to solve a more general class average performance problem, the algorithm is only the second step to improve, but also need to be further improved.

Initialize Total to zero    Initialize counter to zero    Input the first grade (possibly the Sentinel) while the    us Er have not as yet entered the Sentinel add this grade into the running total Add one to the       grade counter       Inpu T the next grade (possibly the Sentinel)    if the counter is not rqual to zero Set the average to the total       divided By the counter       print the average    else       print "No grades were entered"

Figure 2. 8 using markers to control the pseudo-code algorithm to solve the problem of average grade of the class repeatedly

Software Engineering Perspective 2.6

When the details of a pseudo-code algorithm are enough to turn pseudocode into C + + code, programmers can stop the process of gradual refinement from top to bottom, and then easily implement C + + programs.

Figure 2.9 shows the results of C + + programs and sample execution. Although only integer scores are entered, the result can still produce an average score with a decimal point, which is the real number. The int type cannot represent real numbers, and the program introduces a float data type to handle the number of decimal points (also known as floating-point numbers, floatingpoint numbers) and introduces a special coercion type conversion operator (cast operator) to handle the average calculation. These features are described in detail after the program.

Fig. 2.9:fig02_09.cpp//Class Average program with sentinel-controlled repetition. #include <iostream.h>
#include <iomanip.h>int main () {int total, //Sum of gradesgradecounter,//number of grades Enteredgrade; One gradefloat average; Number with the decimal point for average//initialization phasetotal = 0;gradecounter = 0;//processing Phasecout << "Enter grade,-1 to end:"; Cin >> Grade;while (grade!=-1) {total = total + Grade;gradecounter = gradecounter + 1 ; cout << "Enter grade,-1 to end:"; cin >> grade;} Termination Phaseif (Gradecounter! = 0} {average-static_cast< float > (total)/Gradecounter;cout << " Class average is "<< setprecision{2) << setiosflags (ios::fixed | Ios::showpoint) << average << Endl;} Elsecout << "NO grades were entered" << Endl;return 0; Indicate program ended successfully}

Output Result:

   Enter grade, 1 to end:75    enter grade, 1 to end:94    enter grade,-1 to end:97    enter grade,-1 to end:88
   
    enter grade,-1 to end:70    enter grade, 1 to end:64    enter grade,-1    to end:83 enter grade, 1 to End:89
    enter grade, 1 to end:-1    Class average is 82.50
   

Figure 2.9 C + + program and sample execution results with marker control for repetitive resolution of the average class score problem

Note The compound statement in the while loop in Figure 2.9. Without curly braces, the last three statements in the loop body are placed outside the loop, causing the computer to interpret the following code incorrectly:

   While {grade! =-1)       total-total + grade;    Gradecounter = Gradecounter + 1;    cout << "Enter grade,-1 to end:";    CIN >> grade;

If the first result entered by the user is not-l, it will cause an infinite loop.

Note the following statement:

   CIN >>grade;

The user is prompted for input with an output statement earlier.

Programming Tips 2.10

Prompts the user for each keyboard input. The hint should represent the input form and any special input values (such as the tag value entered when the user terminates the loop).

Programming Tips 2.11

In the markup control loop, you are prompted to explicitly specify what the tag value is when you request the input data item.

The mean is not always an integer value, but it is often a value that contains decimals, such as 7.2 or-93.5. These values are called floating-point numbers, represented by the data type float. The variable average is declared as a data type float to obtain a decimal number in the computer result. But Total/gradecounter evaluates to integers because total and gradecounter are integer variables. Dividing two integers is divisible (integer

Division), the fractional part is lost (that is, truncated, truncated). Because the calculation is performed first, the fractional part is lost before the result is assigned to average. To calculate floating-point numbers with integer values, you will need to make a temporary floating-point value for the calculation.

C + + provides a unary coercion type conversion operator (unary cast operator). The following statement:

Average = static cast< float > (total)/gradecounter;

Includes a unary coercion type conversion operator static_cast<float> (), which generates a temporary floating-point value (total) for calculation. This is called an explicit type conversion (explicit conversion) using the coercion type conversion operator. The value stored in total is still an integer, while the calculation is calculated with the floating-point value (the temporary float version of total) divided by the integer gradccounter. The C + + compiler can evaluate an expression that is consistent with the data type of the operand. To ensure consistency in the data type of the operands, the compiler promotes (promotion) the selected operand (also known as implicit type conversion, implicit conversion). For example, in an expression that contains data types float and int, the int operand is promoted to float. In this example, the gradecounter is promoted to float and the result of the floating-point division is assigned to average. All standard data types and their order of Ascension are described later in this chapter. Any data type can be coerced into a type conversion operator, and the static_cast operator consists of a data type name in the keyword STATLC cast angle brackets (<>). The coercion type conversion operator is a unary operator (unary perator), which is an operator with only one operand. The 1th chapter has introduced the two-dollar arithmetic operator. C + + also supports unary positive (+), minus (-) operators, and programmers can write expressions such as 7 and +5. Forcing the type conversion operator to combine right-to-left with precedence over other unary operators, such as the positive (+), negative (-) operators, which are higher than the operators *,/and%, but less than the precedence of parentheses. The precedence table uses static_cast<type> () to represent the coercion type conversion operator.

The formatting feature in Figure 2.9 will be described in detail in the 11th chapter, where we'll start with a brief introduction. Called in the following output statements

Setpreclslon (2):        cout<< "Class average is" << setprecision (2)        << Setiosflaqs (ios::fixed | Ios::showpoint)        << averaqe<< Endl;

Represents the float variable average the number of digits to the right of the print decimal point is two-bit precision (precision), such as 92.37, which is called the parameterized stream operator (parameterized stream manipulator). The program that uses these calls will contain the following preprocessing directives:

        #include <iomanip.h>

Note that the Endl is a non-parameterized stream operator (Nonparameterized stream manipulator) and does not require a Iomanip.h header file. If you do not specify a precision, floating-point values typically output six-bit precision (that is, default precision, precision), but an exception is described later. The Flow manipulation operator Setiosflags (ios::fixed |ios::showpoint) in the above statement sets two output format options ios::fixed and Ios::showpoint. The vertical bar (1) separates multiple options in the Setiosflags call (the vertical bar is described in detail in the 16th chapter). The ios::fixed option allows floating-point values to be output in floating-point format (not the scientific notation, see Chapter LL). Even if the value is an integer, the Ios::showpoint option forces the printing of decimal and trailing o, such as 88. Oo. If you do not use the Ios::showpoint option, C + + displays the integer as 88 and does not print the decimal point and trailing O. When you use the above format in your program, the printed values are rounded to indicate the number of decimal places, but the values in memory remain unchanged. For example, the values 87.945 and 67.543 are output to 87.95 and 67.54, respectively.

Common Programming Error 2.10

If a floating-point application is used, it is considered to be an accurate representation of the deposited value. The crayfish Cambodian. Floating-point employment most computers use an approximate representation.

Programming Tips 2.12

Do not compare the equality and inequality of floating-point numbers, but test whether the absolute difference is less than the value specified.

Although floating-point numbers are not always 100% accurate, they are widely used. For example, when we say normal body temperature is 98.6 (Fahrenheit), it does not need to be accurately expressed if the thermometer shows 98.6 degrees. It could actually be 98.5999473210643 degrees. This shows that 98.6 is sufficient for most applications.

Another way to get a floating-point number is through division. 10 divided by 3 to get 3.333333 ..., is an infinite loop of small compress. The computer allocates only a fixed space to hold this value, so only the approximate value of the floating-point value can be saved.


2016 Postgraduate exam Skills http://www.kyjxy.com/fushi/zhinan/
Postgraduate Exam Preparation Information http://www.kyjxy.com/zhuanshuo/
Policy http://www.kyjxy.com/yuanxiao/zhengce/of Postgraduate College

Computer Foundation of Postgraduate Examination: Construction algorithm and gradual improvement from top to bottom: Case Study 2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.