Statement (14-19)

Source: Internet
Author: User

One: Sequential statements

The principle of organizing straight-line code is to arrange it according to dependencies.

If there is no dependent relationship between the code, then the related statements may be close.

Two: The guiding principle of the IF statement

Put the normal situation behind the IF and not behind the else.

Leave the IF clause followed by a meaningful statement (if the statement block is not empty.) )

Be careful not to reverse the IF and ELSE statements.

Three: The guiding principle of the cycle

Only one position enters the loop.

Put the initialized code in front of the loop.

Use while (true) to indicate an infinite loop.

Avoid empty loops.

A loop is only one thing to do.

Try to confirm that the loop can be terminated.

The loop should be as short as possible, limiting the nesting to within three levels.

Move the contents of the long loop into the subroutine.

Four: Table-driven: is a programming model that looks up information from a table without using logical statements.

Three steps to introduce this table-driven method. The first step is the definition, the previous copy of the book's sentence, has been said to be clear, is to use the table to replace if statement or switch statement. The second step is the reason, can give an example, if there is such a function int gettotaldayinmonth (int month), it enters a month and then returns the total number of days of the month (regardless of the run year, February in 28 days), such as input 5, return 31, Because there were 31 days in May.

One way to do this is:

1//Get total number of days in a January, Monthindex starting from 1 2 int gettotaldayinmonth (int month) 3 {  4     int totalday = 0; 5     if (month = = 2) 6     {7         totalday = 8     } 9     else if (month = = 4 | | month = = 6 | | month = = 9 | | month = =)         Talday = 30;12     }13     else14     {totalday         = 31;16     }17     return totalday;18}

In this writing, the use of logical if judgment, there are a lot of out-of-the-box numbers, such as 2,4,11, and so on, these are called magic number numbers out of the program is very bad, because it is not good to modify and expand, such as the above code for the calculation of the Earth, Now I want you to change the situation on Mars (Mars is different from the Earth, so the number of days per month will be different), you may have to change these magic number, more complex, you may have to because of more days of possibility (assuming that Mars July only 17 days, and September has 21 days), Instead, add more if branches. But if you use a table like this, it makes the program much simpler:

1 const int TOTALDAYTABLE[12] = 2 {3 To,-4, +, +, +, +, +, +,     5  6///For the total number of days in January, Mont Hindex starting from 1 7 int gettotaldayinmonthfromtable (int month) 8 {9     return totaldaytable[month-1];10}

How to compare the use of the table with the code without the table, is it necessary to simplify a lot? More significant is that if a certain number of days change, you can directly modify or expand the totaldaytable on the line, as for the function is divided into no modification.

Well, it should have been solved. The second step is to use the table driver to improve the readability of the source program, making it more concise and easier to modify and expand.

This is the third step and the biggest step in this chapter-how to use the table driver to solve the problem.

The book says that the table method can be subdivided into three kinds:

(1) Direct access

(2) Index access

(3) Ladder access

Direct access is the simplest, looking at the essence of the table is actually going to index "key" to get "value", a bit like getting array values, to set the index, and then Matrix[index] to get the array at the corresponding subscript value, and then as the previous return totaldaytable[ MONTH-1] is the direct use of month-1 as a key, and the value can be directly through the table to obtain.

Now there is a problem, in case the "key" is not directly used? For example, I want to design a child learning animal software, if the child wants to find the cow information, then the screen will print out the characteristics of the cow, and if the child wants to find the dog's information, the screen will print out the dog's information. Obviously, the key here is the animal name, and the value is the corresponding description. The subscript must be an integer, but the animal name is string, what do I do? The hash table in the data structure, of course, it is to calculate the hash value of the string, by the hash value to index the table, but here we do not intend to use the hash value, but by the programmer to design a string to int mapping, how to do it? Very simple Ah, make a menu of their own, so that users can only select the corresponding number, so that "key" into an int ha.

The code is as follows:

 1 class Animal 2 {3 public:4 virtual void print () = 0; 5}; 6 7 class Dog:public Animal 8 {9 public:10 void print () One {cout << "This is Dog ..." << endl;13}14};15 class Cat:public Animal17 {public:19 void print () cout << "This is Cat ..." << endl;22}23};24 class Cow  : public Animal26 {public:28 void print () {cout << ' This is Cow ... ' << endl;31}32 };33 animal* animaltable[] = {New Dog, new Cat, new Cow36};37 int main () () () () () () () () ()---------- Described "<< endl;41 cout <<" 1. Dog "<< Endl <<" 2. Cat "<< Endl <<" 3. Cows "<< endl << endl;42 int choiceindex;  cout << "I choose:"; choiceindex cin >> choiceindex;45 assert (choiceindex >= 1 && <= 3); Animaltable[choiceindex-1]->print (); 

The result of the operation is:

Here with C + + polymorphism, according to different entity objects can call the corresponding print function, but I would like to express the application of table-driven method, please put your eyes on the table animaltable, so that the order is to map the dog into a digital 1,cat map into the number 2. This is a man-made mapping, but the use of more extensive is the hash map, do not know the students to see the data structure bar, hash table can quickly find the sharp weapon, interview often asked.

The second table driver is the index Access table, which applies to the situation, if you run a store, there are 100 kinds of goods, each product has an ID number, but a lot of product descriptions are similar, so only 30 different descriptions, now the problem is to create a commodity and commodity description of the table, how to build? Or does one by one correspond to the above approach? That description will be expanded to 100, and 70 descriptions will be repeated! How to solve this problem? The method is to create a 100-long index, which then points to the corresponding description, noting that different indexes can point to the same description, which solves the problem of table data redundancy.

The third table-driven method is the ladder Access table, it applies to the data is not a fixed value, but a range of problems, such as the conversion of percentile scores into five sub-system (we use excellent, good, medium, qualified, unqualified, Western use of A, B, C, D and F), assuming that the transition relationship is when the score in the 90-100 interval, the award of A, Scores in the 80-90 interval, sentenced to B, scores in the 70-80 interval, sentenced to C, the results in 60-70 interval, sentenced to D, the result is below 60, sentenced to f (failure). Now, the question is, how do you use the table to deal with this range problem? A stupid way is to apply for a 100-long table, and then fill the table with the corresponding level on the line, but this is too wasted space, there is no better way?

In the Code encyclopedia is the use of the table to record the upper limit, but its practical lower limit is also possible, I tried to use the lower bound (a-level lower is the lower limit of the 90,b level is 80 ...) ):

1//Ladder Access table, order Lookup 2 const char gradetable[] = {3     ' A ', ' B ', ' C ', ' D ', ' F ' 4}; 5  6 const int downlimit[] = {7     90 , 80, 70, 60 8}; 9 int Main () {ten     int score = 87;13     int gradelevel = 0;14 while     (gradetable[gradelevel]! = ' F ')     {16
   if (Score < downlimit[gradelevel])             + {+ + + gradelevel;19         }20         else21 {break             ;         }24     }25     cout << "rating" << Gradetable[gradelevel] << endl;26     return 0;27}

The results of the operation are as follows:

Gradelevel is equivalent to a table pointer, which in the program is directed to the correct position by adjusting the table pointer.

The program also has to optimize the place, notice that these lower limits are in order (descending), that can be used in binary search Ah, the program is as follows:

1//Ladder Access table, two-point lookup2ConstChar gradetable[] ={3‘A‘,‘B‘,‘C‘,‘D‘,‘F‘4};56Constint donwlimit_length =4;78Constint downlimit[] ={990,80,70,6010};111213int BinarySearch (IntScore)14{15int low =0;16int high = Donwlimit_length-1;//The largest index of the Downlimit17while (Low <=High18{19int mid = (low + high)/2;20if (Score <Downlimit[mid])21st{Low = mid +1;23}24Elseif (Score >Downlimit[mid])25{High = mid-1;27}28Else29{30ReturnMid31}32}33ReturnLow34}3536 int main () 37 {38 int score = 87; int gradelevel = BinarySearch (score); 40 cout <<  rank  Endl; return 0;42}                 

Statement (14-19)

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.