Chapter 4 of C language programming (fifth edition of Tan Haoqiang) analysis and answers of structural programming exercises

You can also go to the program coffee( https://meta.chengxuka.com ), open the screen question section of the University. You can not only have answers and explanations, but also answer questions online.

Title 1: what is arithmetic operation? What is relational operation? What is logical operation?

Arithmetic operation:

Arithmetic operation, namely "four operations", is a general term for several operations such as addition, subtraction, multiplication, division, power and square.

Among them, addition and subtraction are primary operations, multiplication and division are secondary operations, and power and square are tertiary operations. In a formula, if there are multi-level operations, high-level operations should be carried out first, and then lower-level operations.

The familiar operators in C language include +, -, *, /, + +, --,% and so on.

If only peer operations exist; From left to right; If there are parentheses in the formula, the inside of the parentheses shall be calculated first, and then calculated according to the above rules.

Example: $(1 + 1) ^ {2} * 4 + 5 * 3$

Resolution:

First, operate 1 + 1 in parentheses, and then perform the power operation to obtain the result 4
Then multiply by 4 to get the result 16
Because the priority of multiplication is greater than that of addition, 5 * 3 is performed first to obtain the result of 15
The final addition results in 31
Result: 31

Relational operation:

There are two basic types of relational operations: one is the traditional set operation (Union, difference, intersection, etc.) and the other is the special relational operation (selection, projection, connection, division, outer connection, etc.). In C language, relational operation is usually considered as comparison operation. Compare the two values to judge whether the comparison result meets the given conditions.

Common relational operators include: <, < =, >, > =, = == And so on.

Among them, the first four relational operators (<, < =, >, > =) have the same priority, and the last two (=,! =) have the same priority. The first four are higher than the last two.

For example, > takes precedence over = =. And > and < have the same priority.
In addition, the priority of relational operators is lower than that of arithmetic operators, and the priority of relational operators is higher than that of assignment operators (=).

Logical operation:

In logical algebra, there are three basic logical operations: and, or and not. There are many ways to express logical operations, such as statement description, logical algebra, truth table, Karnaugh map and so on. In C language, logical operations are usually used to connect relational expressions or other logical quantities with logical operators to form logical expressions to test true and false values.

Common logical operators include: & &, ||! Other types

&&: and is a binocular operator. It requires two operands, which means that both operands are true, then the result is true, otherwise the result is false.

For example: (a < b) & & (x > y), which means that (a < b) and (x > y) are true at the same time.

||: is a binocular operator. It requires two operands, which means that as long as either of the two operands is true, the result is true, otherwise the result is false.

For example: (a < b) & & (x > y), which means that if either of (a < b) and (x > y) is true, the result is true.

! It is a monocular operator. Only one operand is required, indicating that the antisense of the operand is taken. If the operand is true, the result is false, and if the operand result is false, the result is true.

For example:! (a > b) means that the result is false when (a > b) is true and true when (a > b) is not true.

If a logical expression contains multiple logical operators, the priority order is:! > & & > |. Of course, if a logical expression contains sub logic enclosed in parentheses, the sub logic judgment in parentheses takes precedence.

Example:

(1 > 2) | (2 > 3) & & (4 > 3) the result is 0
! (1 > 2) | (2 > 3) & & (4 > 3) the result is 1

Note: & & priority is greater than |, ((2 > 3) & & (4 > 3)) cannot be established at the same time, then the result is false, and then conduct logic or operation with the result of (1 > 2), both of which are false, so the first result is false. And the second time! The priority is the highest. First take logical non for the result of (1 > 2), and the result is true, so the result is true.

Topic 2: how to express "true" and "false" in C language? How does the system judge the "true" and "false" of a quantity?

answer:

For a logical expression, if its value is "true", it is represented by 1. If its value is "false", it is represented by 0. However, when judging the value of a logical quantity, the system will take 0 as "false" and non-0 as "true". For example, if the value of 3 & & 5 is "true", the system will give the value of 3 & & 5 as 1.

Topic 3: write the values of the following logical expressions. Let a=3,b=4,c=5.
(1) a+b>c && b==c
(2) al|b + C & & B-C
(3) !(a>b) && !c || 1
(4) !(x=a) && (y=b) && 0
(5) ! (a + b) + C-1 & & B + c/2

answer:

(1) 0
(2) 1
(3) 1
(4) 0
(5) 1

Title 4: there are three integers a, B and C, which are input by the keyboard and output the largest number.

answer:

Method 1: the N-S diagram is shown in Figure 4.1

Answer code:

#include <stdio.h>
int main()
{
    int a, b, c;
    printf("Please enter 3 integers:");
    scanf("%d,%d,%d", &a, &b, &c);
    if (a < b)
        if (b < c)
            printf("max=%d\n", c);
        else
            printf("max=%d\n", b);
    else if (a < c)
        printf("max=%d\n", c);
    else
        printf("max=%d\n", a);
    return 0;
}

Operation results:

Method 2: using conditional expressions can make the program more concise and clear.

#include <stdio.h>
int main()
{
    int a, b, c, temp, max;
    printf("Please enter 3 integers:");
    scanf("%d,%d,%d", &a, &b, &c);
    temp = (a > b) ? a : b;         //Store the larger of a and b into temp
    max = (temp > c) ? temp : c; //Compare the larger of a and b with c and take the largest
    printf("3 The maximum number of integers is%d\n", max);
    return 0;
}

Operation results:

Topic 5: input a positive number less than 1000 from the keyboard and output its square root (if the square root is not an integer, output its integer part). It is required to check whether the data is a positive number less than 1000 after entering it. If not, re-enter is required.

Solution: answer code:

#include <stdio.h>
#include <math.h>
#define M 1000
int main()
{
    int i, k;

    printf("Please enter a value less than%d Integer of i:", M);
    scanf("%d", &i);
    if (i > M)
    {
        printf("The input data does not meet the requirements,Please re-enter a value less than%d Integer of i;", M);
        scanf("%d", &i);
    }
    k = sqrt(i);
    printf("%d The integer part of the square root of is%d\n", i, k);
    return 0;
}

Operation results:

① First time: input correct data.

② Second time: input incorrect data.

Discussion: the number of inputs required by the topic is less than 1000. In order to increase the flexibility of the program, the symbolic constant M is defined as 1000. If the number required by the topic is less than 10000, you only need to modify the define instruction without modifying the main function.

Use the if statement to check whether the input number meets the requirements. If it does not meet the requirements, carry out corresponding processing. From the above program, it is very simple, but it is very useful in practical application. Because after the program is provided to users for use, there is no guarantee that the data entered by users meet the requirements. What if the user inputs data that does not meet the requirements? Without inspection and remedial measures, the procedure cannot be used in practice.

The processing method of this program is to remind the user that "the input data is wrong" and require re input. But just remind once, what if it's wrong again? After learning the loop in Chapter 5, you can change the program to check multiple times until you input it correctly. The procedure is as follows:

#include <stdio.h>
#include <math.h>
#define M 1000
int main()
{
    int i, k;
    printf("Please enter a value less than%d Integer of i:", M);
    scanf("%d", &i);
    while (i > M)
    {
        printf("The input data does not meet the requirements,Please re-enter a value less than%d Integer of i:", M);
        scanf("%d", &i);
    }
    k = sqrt(i);
    printf("%d The integer part of the square root of is%d\n", i, k);
    return 0;
}

Operation results:

The input of data that does not meet the requirements for many times fails until the input of data that meets the requirements.

This inspection method is very important. I hope readers can really master it. This example is only schematic and the program is relatively simple. With this foundation, readers can check and deal with any condition according to this idea, so that the program can run normally without any mistake.

Topic 6: there is a function:

$$ y = \begin{cases} x + y= 1 & (x \lt 1) \\ 2x - 1 & (1 \le x \lt 10) \\ 3x - 11 & (x \le 10) \end{cases} $$

Write a program, input the value of x and output the corresponding value of y.

Answer code:

#include <stdio.h>
#include <math.h>
#define M 1000
int main()
{
    int x, y;
    printf("input x:");
    scanf("%d", &x);
    if (x < 1) // x<1
    {
        y = x;
        printf("x=%3d,  y=x=%d\n", x, y);
    }
    else if (x < 10) // 1=<x<10
    {
        y = 2 * x - 1;
        printf("x=%d,  y=2*x-1=%d\n", x, y);
    }
    else // x> = 10
    {
        y = 3 * x - 11;
        printf("x=%d,  y=3*x-11=%d\n", x, y);
    }
    return 0;
}

Operation results:

Title 7: there is a function:

$$ y = \begin{cases} -1 & (x \lt 0) \\ 0 & (x = 0) \\ 1 & (x \gt 0) \end{cases} $$

Someone has written the following two programs respectively. Please analyze whether they can meet the requirements of the topic. Don't rush to run the program on the computer. First analyze the logic of the above two programs, draw their flow chart and analyze their operation. Then run the program on the computer, observe and analyze the results.

(1)

#include <stdio.h>
int main()
{
    int x, y;
    printf("enter x:");
    scanf("%d", &x);
    y = -1;
    if (x != 0)
        if (x > 0)
            y = 1;
        else
            y = 0;
    printf("x=%d,y=%d\n", x, y);
    return 0;
}

Solution: the flow chart of procedure (1) is shown in Figure 4 2.

It cannot meet the requirements of the subject. If the input x is less than 0, the output y=0. Note the pairing relationship between else and if. The else clause in program (1) is paired with the embedded if statement on line 9, but not with the if statement on line 8.

Operation results:

The value of x is - 6 and the output is y=0. The result is obviously wrong.

(2)

#include <stdio.h>
int main()
{
    int x, y;
    printf("enter x:");
    scanf("%d", &x);
    y = 0;
    if (x >= 0)
        if (x > 0)
            y = 1;
        else
            y = -1;
    printf("x=%d,y=%d\n", x, y);
    return 0;
}

Solution: the flow chart of procedure (2) is shown in Figure 4.3.

Nor can it meet the requirements of the subject. If the input x < 0, the output y=0.

Operation results:

The value of x is - 4 and the output is y=0. The result is obviously wrong. The else clause in program (2) is paired with the embedded if statement on line 9, but not with the if statement on line 8.

Be sure to pay attention to the pairing relationship between if and else. The pairing relationship does not change with the position of the column where if and else appear. For example, else in program (2) is written in the same column as if in line 8, but else is not paired with the if statement in line 8. It is only paired with the nearest if in front of it.

Please compare and analyze the procedure with example 4.5 in Chapter 4 of the textbook to further understand the matching rules of if else.

In order to clarify the logical relationship and avoid errors, the embedded if statement is generally placed in the else clause of the outer layer (as in program 1 in example 4.5). In this way, due to the separation of the outer layer else, the embedded else will not be mistaken for pairing with the outer if, but can only be paired with the embedded if. In this way, it will not be confused. If it is written like program (1) and program (2) in this exercise, it is easy to make mistakes.

It can be compared with the procedure introduced in example 4.5 of this chapter.

Title 8: give the score of 100 point system, and output the grade of 'A', 'B', 'C','D 'and' E '. 'A' for above 90 points, 'B' for 80-89 points, 'C' for 70-70 points,'D 'for 60-69 points and' E 'for below 60 points.

Solution: answer code:

#include <stdio.h>
int main()
{
    float score;
    char grade;
    printf("Please enter student grade:");
    scanf("%f", &score);
    while (score > 100 || score < 0)
    {
        printf("\n Incorrect input,Please re-enter");
        scanf("%f", &score);
    }
    switch ((int)(score / 10))
    {
    case 10:
    case 9:
        grade = 'A';
        break;
    case 8:
        grade = 'B';
        break;
    case 7:
        grade = 'C';
        break;
    case 6:
        grade = 'D';
        break;
    case 5:
    case 4:
    case 3:
    case 2:
    case 1:
    case 0:
        grade = 'E';
    }
    printf("The result is%5.1f,The corresponding level is%c\n", score, grade);
    return 0;
}

Operation results:

Note: check the input data. If it is less than 0 or greater than 100, re input is required. (int) (score/10) is used to cast the value of (score/10) to obtain an integer value. For example, when the value of score is 78, the value of (int) (score/10) is 7. Then execute the statement in case 7 in the switch statement to make grade= 'C'.

Topic 9: give a positive integer with no more than 5 digits. Requirements:

① Find out how many digits it is;

② Output each digit separately;

③ Output the numbers in reverse order. For example, if the original number is 321, 123 should be output.

Solution:

#include <stdio.h>
int main()
{

    int num, indiv, ten, hundred, thousand, ten_thousand, place; //They represent individual, ten, hundred and thousand respectively Tens of thousands and digits
    printf("Please enter an integer(0~99999):");
    scanf("%d", &num);
    if (num > 9999)
        place = 5;
    else if (num > 999)
        place = 4;
    else if (num > 99)
        place = 3;
    else if (num > 9)
        place = 2;
    else
        place = 1;
    printf("digit:%d\n", place);
    printf("Each digit is:");
    ten_thousand = num / 10000;
    thousand = (int)(num - ten_thousand * 10000) / 1000;
    hundred = (int)(num - ten_thousand * 10000 - thousand * 1000) / 100;
    ten = (int)(num - ten_thousand * 10000 - thousand * 1000 - hundred * 100) / 10;
    indiv = (int)(num - ten_thousand * 10000 - thousand * 1000 - hundred * 100 - ten * 10);
    switch (place)
    {
    case 5:
        printf("%d,%d,%d,%d,%d", ten_thousand, thousand, hundred, ten, indiv);
        printf("\n The number in reverse order is:");
        printf("%d%d%d%d%d\n", indiv, ten, hundred, thousand, ten_thousand);
        break;
    case 4:
        printf("%d,%d,%d,%d", thousand, hundred, ten, indiv);
        printf("\n The number in reverse order is:");
        printf("%d%d%d%d\n", indiv, ten, hundred, thousand);
        break;
    case 3:
        printf("%d,%d,%d", hundred, ten, indiv);
        printf("\n The number in reverse order is:");
        printf(" %d% d% d(n", indiv, ten, hundred);
        break;
    case 2:
        printf("%d,%d", ten, indiv);
        printf("\n The number in reverse order is:");
        printf("%d%d\n", indiv, ten);
        break;
    case 1:
        printf("%d", indiv);
        printf("\n The number in reverse order is:");
        printf("%dn", indiv);
        break;
    }
    return 0;
}

Operation results:

Title 10: the bonus paid by the enterprise is based on the profit commission. If the profit I is less than or equal to 100000 yuan, the bonus can be deducted by 10%; When the profit is higher than 100000 yuan and lower than 200000 yuan (100000 < I ≤ 200000), the part lower than 100000 yuan will be deducted by 10%, and the part higher than 100000 yuan can be deducted by 7.5%; When 200 000 < I ≤ 400 000, the Commission for the part less than 200 000 yuan shall still be deducted according to the above method (the same below). 5% commission for the part higher than 200000 yuan; When 400000 < I ≤ 600000 yuan, the part higher than 400000 yuan will be deducted by 3%; When 600 000 < I ≤ 1 000 000, 1.5% commission will be charged for the part higher than 600 000 yuan; When I > 1000000, 1% commission will be charged for the part exceeding 1000000 yuan. Enter the profit I of the current month from the keyboard to calculate the total amount of bonus payable.

requirement:

(1) Programming with if statement;

(2) Program with switch statement.

Solution:

(1) Program with if statement.

Answer code:

#include <stdio.h>
int main()
{

    int i;
    double bonus, bon1, bon2, bon4, bon6, bon10;
    bon1 = 100000 * 0.1;
    bon2 = bon1 + 100000 * 0.075;
    bon4 = bon2 + 100000 * 0.05;
    bon6 = bon4 + 100000 * 0.03;
    bon10 = bon6 + 400000 * 0.015;
    printf("Please enter profit i:");
    scanf("%d", &i);
    if (i <= 100000)
        bonus = i * 0.1;
    else if (i <= 200000)
        bonus = bon1 + (i - 100000) * 0.075;
    else if (i <= 400000)
        bonus = bon2 + (i - 200000) * 0.05;
    else if (i <= 600000)
        bonus = bon4 + (i - 400000) * 0.03;
    else if (i <= 1000000)
        bonus = bon6 + (i - 600000) * 0.015;
    else
        bonus = bon10 + (i - 1000000) * 0.01;
    printf("The bonus is∶%10.2f\n", bonus);
    return 0;
}

Operation results:

The key to this question is to correctly write the bonus calculation formula of each interval. For example, when the profit is 100000 ~ 200000 yuan, the bonus should be composed of two parts:

① The bonus due when the profit is 100000 yuan, i.e. 100000 yuan × 0.1. 


② Bonus for the part above 100000 yuan, i.e. (num-100000) × 0.075 yuan.

Similarly, the bonus of 200000 ~ 400000 yuan should also be composed of two parts:

① The bonus due when the profit is 200000 yuan, i.e. 100000 yuan × 0.1+100 000 × 0.075.

② Bonus for the part of more than 200000 yuan, i.e. (num-200000) × 0.05 yuan.


 in the program, first calculate the bonus of each key point of 100000 yuan, 200000 yuan, 400000 yuan, 600000 yuan and 1000000 yuan, namely bonl1, bon2, bon4, bon6 and bonl0. Then add the bonus of the additional part of each interval. 


(2) Program with switch statement.

The N-S diagram is shown in Figure 4.4.

Answer code:

#include <stdio.h>
int main()
{

    int i;
    double bonus, bon1, bon2, bon4, bon6, bon10;
    int branch;
    bon1 = 100000 * 0.1;
    bon2 = bon1 + 100000 * 0.075;
    bon4 = bon2 + 200000 * 0.05;
    bon6 = bon4 + 200000 * 0.03;
    bon10 = bon6 + 400000 * 0.015;
    printf("Please enter profit i∶");
    scanf("%d", &i);
    branch = i / 100000;
    if (branch > 10)
        branch = 10;
    switch (branch)
    {
    case 0:
        bonus = i * 0.1;
        break;
    case 1:
        bonus = bon1 + (i - 100000) * 0.075;
        break;

    case 2:
    case 3:
        bonus = bon2 + (i - 200000) * 0.05;
        break;
    case 4:
    case 5:
        bonus = bon4 + (i - 400000) * 0.03;
        break;
    case 6:
    case 7:
    case 8:
    case 9:
        bonus = bon6 + (i - 600000) * 0.015;
        break;
    case 10:
        bonus = bon10 + (i - 1000000) * 0.01;
    }
    printf("The bonus is %10.2f\n", bonus);
    return 0;
}

Operation results:

Title 11: input 4 integers and output them in the order from small to large. Solution: this problem uses the method of sequential comparison to arrange its size order. After learning loops and arrays, you can master more sorting methods. 


The procedure is as follows:

#include <stdio.h>
int main()
{

    int t, a, b, c, d;
    printf("Please enter 4 numbers∶");
    scanf("%d,%d,%d,%d", &a, &b, &c, &d);
    printf("a=%d,b=%d,c=%d,d=%d\n", a, b, c, d);
    if (a > b)
    {
        t = a;
        a = b;
        b = t;
    }
    if (a > c)
    {
        t = a;
        a = c;
        c = t;
    }
    if (a > d)
    {
        t = a;
        a = d;
        d = t;
    }
    if (b > c)
    {
        t = b;
        b = c;
        c = t;
    }
    if (b > d)
    {
        t = b;
        b = d;
        d = t;
    }
    if (c > d)
    {
        t = c;
        c = d;
        d = t;
    }
    printf("The sorting results are as follows∶\n");
    printf("%d %d %d %d \n", a, b, c, d);
    return 0;
}

Operation results:

Title 12: there are four round towers with centers of (2,2), (1,2,2), (- 2,1,2), (2,1,2) and circle radius of 1, as shown in Figure 4.5. The height of the four towers is 10m, and there are no buildings outside the towers. Now enter the coordinates of any point to calculate the building height of the point (the height outside the tower is zero).

Solution: the N-S diagram is shown in Figure 4.6.

Answer code:

#include <stdio.h>
int main()
{

    int h = 10;
    float x1 = 2, y1 = 2, x2 = -2, y2 = 2, x3 = -2, y3 = -2, x4 = 2, y4 = -2, x, y, d1, d2, d3, d4;
    printf("Please enter a point(x,y)∶");
    scanf("%f,%f", &x, &y); //Find the distance from the point to each center point
    d1 = (x - x4) * (x - x4) + (y - y4) * (y - y4);
    d2 = (x - x1) * (x - x1) + (y - y1) * (y - y1);
    d3 = (x - x2) * (x - x2) + (y - y2) * (y - y2);
    d4 = (x - x3) * (x - x3) + (y - y3) * (y - y3);
    if (d1 > 1 && d2 > 1 && d3 > 1 && d4 > 1)
        h = 0; //Judge whether the point is outside the tower
    printf("The height of this point is%d\n", h);
    return 0;
}

Operation results:

Notes on leap years:

In Chapter 4 of the textbook, an example of calculating leap years is given. Some readers are not clear about the rules of leap years and write to ask one after another. Therefore, it is necessary to explain the provisions of leap years here:

The actual time for the earth to go round the sun is 365 days, 5 hours, 48 minutes and 46 seconds. If there are only 365 days a year, there will be more than five hours a year. The extra 23 hours, 15 minutes and 4 seconds in four years is almost equal to a day. So it was decided to add one day every four years. However, it is about 45 minutes less than 24 hours a day. If there are 25 leap years every 100 years, there will be 18:43:20 less, which is almost equal to a day, which is obviously inappropriate. 


It can be calculated that there will be 5 hours, 48 minutes and 46 seconds more every year, and 581 hours, 16 minutes and 40 seconds more in 100 years. And 25 leap years take 25 × 24 = 600 hours. 581 hours, 16 minutes and 40 seconds is only enough for 24 leap years × 24 = 576 hours), so we decided to arrange only 24 leap years every 100 years (century year is not regarded as leap year). But in this way, there are 5 hours, 16 minutes and 40 seconds more every 100 years (581 hours, 16 minutes and 40 seconds - 576 hours), so it is decided to add a leap year every 400 years. This is closer to the actual situation. 


Based on the above, it is decided that leap years shall be calculated according to the following rules:

Leap years should be divisible by 4 (for example, 2004 is a leap year, but 2001 is not a leap year), but not all years that can be divisible by 4 are leap years. In the year that can be divided by 100, only the year that can be divided by 400 at the same time is a leap year (for example, 2000 is a leap year), and the year that can be divided by 100 but cannot be divided by 400 (for example, 1800, 1900 and 2100) is not a leap year. This is an internationally recognized rule. It is not accurate to say that "the year divisible by 4 is a leap year".

The methods and procedures introduced in the textbook are correct. 



Tags: C

Posted by rimelta on Fri, 15 Apr 2022 11:56:46 +0930