Code comments and analysis: Exercise 3-2, Word Length (word)

Source: Internet
Author: User

Received from a group memberCodeCan't help commenting. Please correct me.

Statement 《AlgorithmThe entry to the competition classic P50 has such a question. I will give the following detailed descriptions:

Exercise 3-2, Word Length (Word). c
Enter several words and output their average length. A word contains only uppercase and lowercase letters, separated by one or more spaces.

As described in the question, it meansThere are only two types of characters that a user can enter: letters, or spaces.This must be clear. Whether it is a competition or a self-practice, it is very important to understand the requirements of the questions (customers.

In my opinion, there are more than one solution strategy for this question. For example, the policy I used for the solution is:

Note:
To solve this question, you need to use string knowledge. String, which is a one-dimensional character array.
Enter Ctrl + Z, press enter, and press Enter.
Policy:
Scanf ("% s",...); when a space is encountered, it is automatically truncated. It is suitable for this type of environment.
Strlen (); used to calculate the length of a string
Procedure:
1. Read a word;
2. Counter increment 1
3. Calculate the word length and accumulate the total length.
4. Total length/Counter ----> Average Length

The Code provided by the student in the group is as follows:

Source1.c

 0001 # Include <stdio. h> 0002 # Include <string. h> 0003 # Include <ctype. h> 0004 # Define a 100000 + 10/* assume the maximum number of characters entered by the user */ 0005 Int A [a];/* store the character data entered by the user */ 0006 Main () 0007 { 0008 Int y = 0, 0009 TOT = 0,/* total number of letters entered by the user */ 0010 WORD = 1;/* Number of words (it is inappropriate to initialize to 1 here, because the user may not enter any letters, but only enter spaces. */0011 Char I = 0; 0012 Gets (); 0013 I = strlen (); 0014 TOT = I; 0015 For (; y <I; y ++ ){ 0016 If (isspace (A [y]) {/* for how to use the isspace () function, see: http://www.kuqin.com/clib/ctype/isspace.html Note: user input actually only contains spaces and letters */ 0017 TOT = tot-1; 0018 WORD = word + 1; 0019 } 0020 } 0021 Y = 0;0022 Y = TOT/word; 0023 Printf ("% d \ n", y ); 0024 Return 0; 0025 }

Unfortunately, this student did not give a detailed explanation of the solution. He threw a piece of code (source1.c) and said something wrong. I 'd like to help you correct it. To be honest, he should describe his own ideas and add some necessary comments in the Code (I added the above comments) to explain why source1.c should be written like this, you can also help him. Next, I had to guess his ideas.

The source1.c policy is:

    1. Read all user data into array. Int A [a] is an incorrect expression and should be char a [A].
    2. The original author wanted to use I to represent the number of characters entered by the user, but wrote char I = 0; (11th rows), which is obviously wrong! The correct expression should be: int I; here I does not need to be initialized to 0, and I is assigned to all 13th rows.
    3. Use y as the subscript of the array. Starting from the subscript 0, scan the entire array A and analyze the total number of letters tot and Word Count word. Obviously, the tot and word here should be int type. The code from 14th rows to 20th rows completes this work. Specifically, the original author first assumes that all the characters are letters, so there is a 14th-row tot = I; assumption, and then scanning the process, each encounter a space, reduce tot by 1. This part is correct. However, unfortunately, the original author's idea of word calculation is wrong:Because the user may enter many consecutive spaces, it is considered that a word is added when there is no space. So how can we determine that we have scanned a new word? For more information, see the description below.
    4. Finally, the original author calculated and output the average length of words from 21st rows to 23rd rows using Y. There is also an obvious problem here: Y, TOT, word types are all int, here the average length of words is obviously there is a possibility of decimal. Just like calculating the average age of a class student:The average value is usually a real number (with decimal digits ).
    5. Note that the space () function determines that the "blank symbols" refer to the "blank characters refer to space, horizontal tabulation, vertical tabulation, page feed, carriage return, and line feed. Note: user input only contains spaces and letters.

After analyzing many problems of source1.c, let's rewrite this part of code using the original author's ideas. The code I provided is as follows:

Source2.c

 0001 # Include <stdio. h> 0002 # Include <string. h> 0003 # Include <ctype. h> 0004 # Define a 100000 + 10/* assume the maximum number of characters entered by the user */ 0005 Main () 0006 { 0007 Char A [a];/* store the character data entered by the user */ 0008 Int y, 0009 TOT = 0,/* total number of letters entered by the user */ 0010 WORD = 0,/* Number of words */ 0011 I; 0012 Gets (); 0013 I = strlen (); 0014 TOT = I; 0015 For (y = 0; y <I; y ++ ){ 0016 If (isspace (A [y]) tot = tot-1; 0017 If ( 0018 (Y = 0 &&! Isspace (A [y])/* If the element whose subscript is 0 is not a space, a word is found. (Special processing is required at the beginning of the array .) */ 0019 | 0020 (Y> 0 & isspace (A [Y-1]) &! Isspace (A [y])/* If an element whose subscript is greater than 0 is not a space, and the first element of the element is a space, A word is found */ 0021 ) Word = word + 1; 0022 } 0023 If (WORD = 0) printf ("no words entered ");0024 Else printf ("the average word length is % F", (TOT * 1.0)/Word ); 0025 Return 0; 0026 }

Key issues:How can we determine that we have scanned a new word?The corresponding code is 16th ~ of source2.c ~ 21 rows.

The testing of source2.c is as follows:

D: \ Temp> TCC-run test2.c

Smart thanks

The average word length is 5.500000

D: \ Temp> TCC-run test2.c

Smart thanks

The average word length is 5.500000

D: \ Temp> TCC-run test2.c

S Mart T hanks

The average word length is 2.750000

D: \ Temp> TCC-run test2.c

No words entered

Summary and reflection:

    1. Before solving the problem, you must understand the meaning of the problem. What does she want me to do? What is the data input by the user? What kind of output should I have?
    2. Use appropriate data types to express the data involved in the problem. For example, you can use character arrays to store user input strings, use floating-point data to store average values, and use integer data to store count values ...... The choice of floating point type and integer type is often the place where beginners encounter errors.
    3. The processing of the "boundary condition" should be carefully considered. For example, the first line of source2.c is a special judgment on the character a [0. Note that the array subscript starts from 0, and the array does not have elements such as a [-1.
    4. When writing code, you must make comments and instructions. Otherwise, you may look so tired that others may look so painful! For more information about how to write comments, see mySource code.
    5. Perform more tests.

So far, the whole world is quiet.

Thank you!

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.