Location>code7788 >text

Computer 2 C in 2 Months - Question (5) Explanation

Popularity:246 ℃/2024-10-29 11:07:26

1. Preamble

In this post we explain2 months to get computer level 2 C language-Questions 5

真题5-程序评分

2. Procedural fill-in-the-blank questions

2.1 Title requirements

真题5-程序填空

2.2 Code provided

#include <>

double fun(int n) {
    int    i;
    double s, t;
    /**********found**********/
    s = __1__;
    /**********found**********/
    for (i = 1; i <= __2__; i++) {
        t = 2.0 * i;
        /**********found**********/
        s = s + (2.0 * i - 1) * (2.0 * i + 1) / __3__;
    }
    return s;
}

main() {
    int n = -1;
    while (n < 0) {
        printf("Please input(n>0): ");
        scanf("%d", &n);
    }
    printf("\nThe result is: %f\n", fun(n));
    getchar();
}

2.3 Problem solving ideas

This question is a typical paper tiger question, it as the first question of programming will be in the examination room to pressure you to do something on the topic, make this question as if it is difficult to look, in fact, the main code are written, and also gives the formula of the law, then we only need to slightly out of the way, you can take this question.

(prefix indicating ordinal number, e.g. first, number two etc)(1) Fill in the blanks at:

This is the name given to the variables assignment, you can see that thefun() The end of the function isreturn s; returns it as a function return value, from which it follows that thes is the variable that holds the sum of the first n items, so here we assign it a value of 0 to initialize the variable and prevent the program from starting to run with thes Storedjunk value

s = 0; // initialize to 0

(prefix indicating ordinal number, e.g. first, number two etc)(2) Fill in the blanks at:

There is a missing loop condition here, in the equation given in the question it is computed from 1 to n. In the loopi Doing this very thing, soiLess than or equal to a formal parametern If you are eligible, fill in heren

for (i = 1; i <= n; i++) {  // 1 ~ n

(prefix indicating ordinal number, e.g. first, number two etc)(3) Fill in the blanks at:

Let's look at this equation alone(2.0 * i - 1) * (2.0 * i + 1) / __3__The third place of the vacancy corresponds to the denominator part of the equation.(2*n)²The Variablest At the beginning of the loop, the loop is passed through thet = 2.0 * i; Having already done the calculations in the denominator brackets, we just need to use thet * t Just calculate the square.

s = s + (2.0 * i - 1) * (2.0 * i + 1) / (t * t); // Calculate t multiplied by t, i.e., the square of t

Of course, squaring can also be done using functions from the C standard library - thepow function, which can be used to compute powers, is defined in the Header files are included in the header file, and use requires the inclusion of the header file.

// The C library function double pow(double x, double y) returns x to the yth power, i.e., x ^ y. // This function can be used to return the yth power.
#include <> // Include headers when using the pow function.

s = s + (2.0 * i - 1) * (2.0 * i + 1) / pow(t, 2); // Computes t to the second power, i.e., t squared.

The topic requires that no other functions be altered and no lines be added or deleted, so here I continue to use thet * t Calculate the square, you can usually program directly withpow function.

2.4 Code Implementation

Fill in the complete code:

#include <>

double fun(int n) {
    int i;
    double s, t;
    /**********found**********/
    s = 0; // initialize to 0
    /**********found**********/
    for (i = 1; i <= n; i++) { // 1 ~ n
        t = 2.0 * i;
        /**********found**********/
        s = s + (2.0 * i - 1) * (2.0 * i + 1) / (t * t); // count t multiply (mathematics) t,assume (office) t square (as in square foot, square mile, square root)
    }
    return s;
}

int main() {
    int n = -1;
    while (n < 0) {
        printf("Please input(n>0): ");
        scanf("%d", &n);
    }
    printf("\nThe result is: %f\n", fun(n));
    getchar();
}

Tip: To ensure that the code works correctly, please test and run it in the corresponding topic of the question bank programming environment.

3. Program modification questions

3.1 Title requirements

真题5-程序修改

3.2 Code provided

#include <>
#pragma warning(disable : 4996)

int my_isalpha(char c) {
    if (c >= 'A' && c <= 'Z')
        return 1; else if (c >= 'A' && c <= 'Z')
    else if (c >= 'a' && c <= 'z')
        return -1; else
    c <= 'Z') return -1; else
        return 0; }
}

void a() {
    char ch; int sort; int
    int sort; } void a() { char ch; int sort; printf
    printf("This program determines the kind of character you type from the keyboard, please enter the character (string): \n"); } void a() { char ch; int sort; int sort
    do {
        ch = getchar(); if (ch !
        if (ch ! = '\n') {
            sort = my_isalpha(ch);
            /**********************found***********************/
            switch (-1 <= sort && sort <= 1) {
                case 1.
                    printf("%c", '*');
                    break;
                    /**********************found***********************/
                case -1: printf("%c", '*'); break; /found/
                    printf("%c", '#');
                case 0: printf("%c", '#'); /found/
                    printf("%c", '?'); case 0. ;)
            }
        }
        /**********************found***********************/
    } while (ch == '\n');
    printf("%c", '\n'); }
}

void main() {
    a(); }
}

3.3 Problem solving ideas

This question focuses onswitch Usage of the statement.

(prefix indicating ordinal number, e.g. first, number two etc)(1) The changes have been made:

switch The expression in parentheses (i.e., the control expression) must be an integer or a type that can be converted to an integer.case tag must also be a constant expression, and must be associated with theswitch is compatible with the control expression type of

So instead of that bunch of relational, logical operations, just put in thesort Just fine, it storesmy_isalpha The return value of the function.

switch (sort) {

(prefix indicating ordinal number, e.g. first, number two etc)(2) The changes have been made:

existswitch In the statementbreak statement is used to terminate the currentcase branch is executed and jumps out of theswitch statement, preventing the program from continuing to execute subsequentcase Branching out.

After changing the first place, running the program and typing in a lowercase letter returns the#?This is due to the fact that thecase -1: is not added to the branch of thebreak statement, resulting in not being able to jump out of theswitch statement after executing thecase -1: The branch was then executedcase -1: Branching out, it's clear that our program isn't working the way we want it to.

At this point we need to add each of the two branchesbreak statement will suffice.

We can add more in the subsequent development of the programdefault Branches that are used to perform operations that are not within the condition, thus enhancing the robustness of the program.

case -1:
    printf("%c", '#');
    break;
case 0:
    printf("%c", '?');
    break;

(prefix indicating ordinal number, e.g. first, number two etc)(3) The changes have been made:

do while statement will first execute the program in the loop once, and then determine whether the loop condition is true, true, then continue the loop, otherwise execute the program after the loop.

ch stores a single character entered by the keyboard.'\n' is an escape sequence used to represent a line break, corresponding to the return key (Enter) on the keyboard.

I didn't find any errors here, the code provided iswhile (ch == '\n');If you change it, you can only change it towhile (ch != '\n');, both codes I can get full points for when I submit them separately.

Run these two programs separately, and there is no difference between the two programs if you follow the requirement to type the characters first and then hit enter.

But without typing the characters first and hitting enter directly, then the difference comes:while (ch == '\n'); No matter how many times you hit enter, the loop doesn't stop because it matches thech == '\n'This condition, which loops until you enter a character that is not a carriage return.

do {
    ch = getchar();
    if (ch != '\n') {
        // ……
    }
    /**********************found***********************/
} while (ch == '\n');

(indicates contrast)while (ch != '\n');What about it? If you first hit enter at this pointchStored is the escape character for a carriage return'\n'The loop condition isch != '\n', since the loop condition is not met, the next loop is not performed, but thewhileThe following statement is up.

do {
    ch = getchar();
    if (ch != '\n') {
        // ……
    }
    /**********************found***********************/
} while (ch != '\n');

This is the difference between the two, you need to pay attention to the conditions of the loop / judgment in the future programming Oh.

3.4 Code Implementation

Modified code:

#include <>
#pragma warning(disable : 4996)
int my_isalpha(char c) {
    if (c >= 'A' && c <= 'Z')
        return 1; else if (c >= 'A' && c <= 'Z')
    else if (c >= 'a' && c <= 'z')
        return -1; else
    c <= 'Z') return -1; else
        return 0; }
}
void a() {
    char ch; int sort; int
    int sort; } void a() { char ch; int sort
    printf("This program determines the kind of character you type from the keyboard, please enter the character (string): \n"); }void a() { char ch; int sort; printf("This program determines the kind of character you type from the keyboard, please enter the character (string): \n"); }void a()
    do {
        ch = getchar(); if (ch !
        if (ch ! = '\n') {
            sort = my_isalpha(ch);
            /**********************found***********************/
            switch (sort) {
                case 1.
                    printf("%c", '*');
                    break.
                    /**********************found***********************/
                case -1.
                    printf("%c", '#');
                    break; /found/
                case 0: printf("%c", '?
                    printf("%c", '?') break; case 0: printf("%c", '?')
                    break; }
            }
        }
        /**********************found***********************/
    } while (ch ! = '\n');
    printf("%c", '\n');
}
void main() {
    a(); }
}

Tip: To ensure that the code works correctly, please test and run it in the corresponding topic of the question bank programming environment.

4. Programming questions

4.1 Title requirements

真题5-程序设计

4.2 Code provided

#include <>
#pragma warning(disable : 4996)
double fun(int n) {
}
main() {
    int n; int
    double s; void NONO(); void NONO(); void NONO()
    
    printf("Input n: "); scanf("%d", &n);
    scanf("%d", &n);
    getchar(); s = fun(n); s
    s = fun(n);
    printf("s=%f\n", s);
    NONO();
    getchar();
}
void NONO() { /* Please open the file, input the test data, call the fun function, output the data, and close the file within this function. */
    FILE * rf, *wf.
    int n, i;
    double s; rf = fopen("")
    rf = fopen("", "r");
    wf = fopen("", "w");
    for (i = 0; i < 10; i++) {
        fscanf(rf, "%d", &n);
        s = fun(n);
        fprintf(wf, "%lf\n", s);
    }
    fclose(rf);
    fclose(wf);
}

4.3 Problem Solving Ideas

The question asks to compute the value of a polynomial given that the first term of the polynomial is 1 and the second through nth terms are sums that compute the factorial inverse.

We can useSnis used as a variable to store the sum, after which the values of the factorials are obtained by cyclic multiplication, and finally the reciprocal of each factorial is computed and accumulated toSn

There was a small problem when submitting, the program worked fine, but the submission scored 0 points. After testing the program, you just need to change theNONO();Just comment the statement and submit it again.

4.4 Code Implementation

Fill in the complete code:

#include <>
#pragma warning(disable : 4996)
double fun(int n) {
    int i = 0; double Sn = 1.0; // Store the sum, the first term of the polynomial.
    double Sn = 1.0; // Store the sum, the first term of the polynomial is 1.
    unsigned long factorial = 1; // store the cumulative sum, the first term of the polynomial is 1

    for (i = 1; i <= n; i++) { // iterate through 1~n, noting that i starts at 1
        factorial *= i; // compute factorials from 1 to n separately
        Sn += 1.0 / factorial; // Compute the reciprocal of the factorial and add it to the sum variable.
    }

    return Sn; }
}
main() {
    return Sn; } main() { int n; double s
    int n; double s; void NONO(); void NONO()
    void NONO(); printf("Input n: "); }
    printf("Input n: "); scanf("%d", &n);
    scanf("%d", &n);
    getchar(); s = fun(n); s
    s = fun(n);
    printf("s=%f\n", s);
    NONO(); // If the score doesn't pass, just comment this out and submit it again
    getchar();
}
void NONO() { /* Please open the file, input the test data, call the fun function, output the data, and close the file within this function. */
    FILE * rf, *wf.
    int n, i;
    double s; rf = fopen("")
    rf = fopen("", "r");
    wf = fopen("", "w");
    for (i = 0; i < 10; i++) {
        fscanf(rf, "%d", &n);
        s = fun(n);
        fprintf(wf, "%lf\n", s);
    }
    fclose(rf);
    fclose(wf);
}

Tip: To ensure that the code works correctly, please test and run it in the corresponding topic of the question bank programming environment.

5. Postscript

This is the end of this blog, if you have questions or suggestions you are welcome to leave them in the comments section.