C Language Programming sixth time job

Source: Internet
Author: User
Tags goto

C Language Programming sixth time job

tags (space delimited): C language

In a blink of an eye, we entered the new week again. The last week we learned mainly the while and do-while statements of the loop structure. In this way, we have mastered the topic language of the loop in C. Of course, we also learned how to use break and contini in circular statements in class. So let's start with a summary of what the C language has learned in the previous week.

(a) Correct the wrong question

The source program with the error is as follows:

#include<stdio.h>int main(void){    int flag,n;    double eps,item,s;        printf("Input eps: ");    scanf("%f",&eps);    flag = 1;    s = 0;    n = 1;    do{        item = 1/ n;        s = s + flag * item;          flag = -flag;        n = n + 3;    }while( item < eps)    printf( "s = %f\n",s);        return 0;}

The topic requirements are:

Sequence summation: Enter a positive real number EPS, calculate the sequence portion and 1-1/4 + 1/7-1/10 + ..., the absolute value of the last item is less than the EPS (keep 6 decimal places).
Input/Output Sample:
Input eps:1e-4
s = 0.835699

First, we will attempt to compile this source program once, compile an error, and the error prompt is as follows:

警告  C4477   “scanf”: 格式字符串“%f”需要类型“float *”的参数,但可变参数 1 拥有了类型“double *”(定位于第9行)错误(活动)  E0065   应输入“;”(定位于第18行)错误  C2146   语法错误: 缺少“;”(在标识符“printf”的前面)(定位于第18行)   

We have gradually modified according to the error prompt:

    • Do-while The loop statement requires a semicolon to end.
    • No semicolon causes a syntax error before the printf statement.

      These two errors are caused by the same reasons that are not familiar with the Do-while statement. A different point between the Do-while statement and the for statement and the while statement is that the for and while statements are similar to the IF statement, where the IF (for,while) keyword is the same line of code that is combined with the following line of code to form a statement. And the Do-while statement is not the same.

      Is the end flag of the C statement, while there is this
      while (loop condition)
      {Loop body};
      do{cyclic body}while (cyclic condition);

The summary error reason is: Unfamiliar with the Do-while statement, does not add a semicolon after the while.

Accordingly, the amendment is as follows: Add the semicolon ";" after line 19th while statement.

    • When a variable is declared as a double type, the scanf statement should use%LF to declare the primitive. The%LF is of the type long*.

The summary error is due to the format specifier that is declared as a double type but does not change the format specifier of the input statement to double precision.

Accordingly, the amendment is as follows: The 9th line is %f changed to %lf .

Thus, the revised source code for this department is as follows:

#include<stdio.h>int main(void){    int flag,n;    double eps,item,s;        printf("Input eps: ");    scanf("%lf",&eps);    flag = 1;    s = 0;    n = 1;    do{        item = 1/ n;        s = s + flag * item;          flag = -flag;        n = n + 3;    }while( item < eps);    printf( "s = %f\n",s);        return 0;}

The result of this source code operation is as follows:

We see that the result is 1.000000, and this result is a result of the loop body running once, and we infer that there is a problem with the condition statement of the loop body. We check that the judgment statement in the while bracket finds an error, the first item value is almost certainly greater than the smaller precision we entered, and then exits the loop, where the condition of the loop continues rather than the end.

Finally, the reason for the error: confusing the Do-while statement after the sentence in parentheses is the true continuation loop.

Accordingly, the opinion is modified as follows: Modify the 18th line }while(item < eps) to }while(item > eps) .
The result of the operation is:

We find that the result is the same as before, and I infer that there is a problem in the operation, whereby we check that the operation statement finds that the assignment statement for Line 14th is divided into two variables of type int, and we want to get the floating-point type.
Accordingly, the amendment is: will be item = 1 / n changed to item = 1.0 / n .
The result of the operation is:

I found that the program running results are very close to the correct results, indicating that the loop body run less or more times, check the cycle conditions and according to test instructions: accurate to the last item absolute value is less than EPS. That is, finally, when a number is less than precision, you need to add it to the result.

Cause of error: The condition that the loop continues and ends is not understood. (My mistake)

Modification method: Line 18th is modified again }while( item <= eps ) .
Finally the correct source code is as follows:

#include<stdio.h>int main(void){    int flag,n;    double eps,item,s;        printf("Input eps: ");    scanf("%lf",&eps);    flag = 1;    s = 0;    n = 1;    do{        item = 1/ n;        s = s + flag * item;          flag = -flag;        n = n + 3;    }while( item < eps);    printf( "s = %f\n",s);        return 0;}
(ii) Study Summary 1. while(1)And for(;;)
    • The Loop judgment statement for while (1) is always true so the loop statement will continue to loop when no break statement ends the loop. for (;;) Statements are also similar to while (1) are infinite loops. for(;;)and the for(;1;) same. Infinite loops apply to loops that do not know the number of times a loop should run, such as looking for a number, which needs to be judged after 1 to determine whether the number meets the criteria. Just like the 4th question of our PTA this week, The infinite loop is the simplest, like Han soldiers of.
    • To ensure that an infinite loop is able to run and produce results in the way that it wants, you need to exit the loop at the right time, and to do this we can use the break statement to exit the loop, and sometimes we can use a goto statement. As long as you can guarantee the logic.
2. Selection of circular statements
    • (i) Number of cycles known: for
      Using a For loop typically causes the statement block to repeat the specified number of times. We use the For loop counter to specify the number of cycles. For example, the 2nd question of the loop structure (ii) directly specifies the number of data that will be entered accordingly, we use the For statement to loop.
      The source code for question 2nd is as follows:
 //2 Guess number game # include <stdio.h>int main (void) {int true_x = 0,try_max = 0,x = 0,try_num = 0;    scanf ("%d%d", &true_x,&try_max);     Prepare to enter the loop.    int flag = 0;    unsigned int i = 1;                for (; I <= Try_max; i++) {scanf ("%d", &x);            if (x < 0) {printf ("Game over");            flag = 1;        Break        } else if (x = = true_x) {break;}            else if (x > true_x) {try_num++;        if (I < Try_max) {printf ("Too big\n");}            } else {try_num++;        if ("I < Try_max") {printf ("Too small\n");}     }}//judge the situation.        if (flag = = 0) {if (Try_num = = 0) {printf ("bingo!");}        else if (Try_num < 3) {printf ("Lucky you!");}        else if (Try_num < Try_max) {printf ("good guess!");}    else {printf ("Game over");} } return 0;  

And almost all of the circular structures that specify the number of input numbers the most appropriate loop type is the For loop.

    • (b) The number of cycles is unknown, but the loop condition is clear when entering the loop: while statement
    • (c) The number of cycles is unknown, and the loop condition is unknown when entering the loop, it needs to be clear in the loop body: do-while statement.

I think that while statements and Do-while statements are very small, the main difference between them is that the Do-while statement will run once, but most of the topic or the actual cycle will be executed more than once, The judging time of the cyclic condition can also modify the order of the statements within the loop block to achieve the same effect. For example, my PTA cycle Structure (ii) in the 4, 5, 6, 7 are used in the Do-while statement. In the normal case, the Do-while statement is not so common compared to the other two statements.
For example, the seventh question of the loop structure (ii) requires an infinite loop, and there is definitely a loop at least once, so we can use any one of the for, while, do-while statements as we learned in the first question.
The 7th question source code:

//250#include <stdio.h>int main(void){    int x = 0,i = 0;    //开始循环。    i = 1;  //初始化i的值。    do{        scanf("%d",&x);        if(x == 250)        {            printf("%d\n",i);            break;        }        else        {            i++;        }    } while(1);    return 0;}

And the general use of the while statement of the sixth question I use is the Do-while statement.
The source code is as follows:

6. The number that falls into the trap # include <stdio.h>int main (void) {int N = 0,i = 0,sum = 0,n1 = 0;        int digit1 = 0,digit2 = 0,digit3 = 0,DIGIT4 = 0,digit5 = 0;    scanf ("%d", &n);  i = 1;    Initializes the value of I, and I is the counter.    int flag = 0;            do{if (flag = = 1) {N = N1;        Goto Calculate;             } else {Calculate://Connect to the above loop.            if (n <= 9) {sum = n;                } else if (n <=) {digit1 = n 10;                Digit2 = N/10;            sum = digit1 + digit2;                } else if (n <= 999) {digit1 = n 10;                Digit2 = (n%100-digit1)/10;                Digit3 = (n%1000-digit2*10-digit1)/100;            sum = digit1 + digit2 + digit3;                } else if (n <= 9999) {digit1 = n 10;                Digit2 = (n%100-digit1)/10; Digit3 = (n%1000-DIGIT2*10-DIGIT1)/100;                DIGIT4 = (n%10000-digit3*100-digit2*10-digit1)/1000;            sum = digit1 + digit2 + digit3 + digit4;                } else {digit1 = N% 10;                Digit2 = (n%100-digit1)/10;                Digit3 = (n%1000-digit2*10-digit1)/100;                DIGIT4 = (n%10000-digit3*100-digit2*10-digit1)/1000;                Digit5 = (n%100000-digit4*1000-digit3*100-digit2*10-digit1)/10000;            sum = digit1 + digit2 + digit3 + digit4 + digit5;                } N1 = sum*3 + 1;                printf ("%d:%d\n", i,n1);                i++;        flag = 1;        }} while (N1! = N);  return 0;}

My problem algorithm is very primitive, the simpler algorithm is to use a loop to deal with him.

while(N != 0){    digit = N % 10;    N = N / 10;    sum += digit;}

A loop can deal with the problem I have used a lot of judgment to finish.

3.for, while, do-while examples

Title: Enter a batch of student scores, ending with 1 to calculate the student's average score.

The source code for the while statement is as follows:

#include <stdio.h>int main(){    double sum = 0.0, x = 0.0, average = 0.0;    int num = 0;    sum = 0.0;    num = 0;    while (1)   //无限循环    {        scanf("%lf", &x);        if (x == -1)        {            break;        }        sum += x;        num++;    }    average = sum / num;    printf("平均成绩为%f", average);    return 0;}

The source code for the For statement is as follows:

#include <stdio.h>int main(){    double sum = 0.0, x = 0.0, average = 0.0;    int num = 0;    sum = 0.0;    num = 0;    for(;;) //无限循环    {        scanf("%lf", &x);        if (x == -1)        {            break;        }        sum += x;        num++;    }    average = sum / num;    printf("平均成绩为%f", average);    return 0;}

You can see the similarity between using the while statement and the for statement, because you want to use an infinite loop. Let's take a look at the example using the Do-while statement:

#include <stdio.h>int main(){    double sum = 0.0, x = 0.0, average = 0.0;    int num = 0;    sum = 0.0;    num = 0;    scanf("%lf", &x);    if (x == -1)    {        average = 0.0;    }    else    {        do {            scanf("%lf", &x);            if (x == -1)            {                break;            }            sum += x;            num++;        } while (1);        average = sum / num;    }    printf("平均成绩为%f", average);    return 0;}

Using the Do-while statement is not the same as using the for and while statements because it is more complex to exclude users from entering-1 directly at the first number.

It is more appropriate to use the while statement on this topic. The reasons are as follows:

    • It looks more intuitive than the for statement.
    • The gap with the Do-while statement is very obvious, the Do-while statement needs more thinking and the program is more complex, and the reason is that the Do-while statement will run at least once, but there are some special cases that will make the loop body does not run.
4. Program Comparison

Source code one is as follows:

#include<stdio.h>int main(){    int n,s,i;    s = 0;    for(i = 1; i <= 10; i++)    {        scanf("%d",&n);             if(n % 2 == 0)            break;              s = s + n;          }    printf("s = %d\n",s);    return 0;}

Source code II is as follows:

#include<stdio.h>int main(){    int n,s,i;    s = 0;    for(i = 1; i <= 10; i++)    {        scanf("%d",&n);             if(n % 2 == 0)            continue;               s = s + n;          }    printf("s = %d\n",s);    return 0;}

The results of code Input 1 through 10 are as follows:

The result of code two inputs 1 to 10 is as follows:

Code Analysis:
Code two is obviously more consistent with the program design target than the code one, seeking 10 number of odd numbers, and the result of code one run does not make any sense. The reason for this is whether you are using the Continue continuation statement or the break jump statement. We can also modify the source program to achieve the intended purpose, but are not as concise as the continue statement.

The difference between a continue statement and a break statement:
The first time we contacted the break statement was when we were learning switch switch statements, when we ended a switch with a break statement, or the penetration of the switch statement could easily cause errors. In the for, while, Do-while loops, the action is the first statement that jumps out of the loop where the break statement is located. However, unlike the continue statement, it does not cause the loop to end completely, but simply skips the statement after the continue statement in this iteration, forcing the next iteration to be specified. Continue statements are mainly to speed up the operation of the loop.

(iii) Experimental Summary 1. The simple staggered sequence part of the given precision and

The subject asks to write the program, computes the sequence part and 1-1/4 + 1/7-1/10 + ... The absolute value of the last item is not greater than the given precision EPs.

The flowchart is as follows:

The source code is as follows:

#include <stdio.h>   #include <float.h>int main(void){    int flag = 0,t = 0;    double eps = 0.0,sum = 0.0,pre = 0.0;        scanf("%lf",&eps);  //要求用户输入精度。        if(eps == 0.0)  //判断用户是否输入非法数据。    {        printf("ERROR:请输入正确的精度。");    }     else    {        t = 1;        sum = 0;        flag = 1;        pre = DBL_MAX;        //开始进行循环。        while(pre > eps)        {            pre = 1.0/t;            sum += flag * (1.0/t);            t += 3;            flag = -flag;        }                    printf("sum = %f",sum);     }        return 0;}

This problem may occur in the cyclic conditions, the topic requires the last one less than the accuracy of the number plus, but if the wrong condition will make the data less than once. You can modify the code order in the loop body to choose whether to add the last bit less than the precision data, such pre = 1.0 / t; that the statement on line 27th can make the program does not add the last set of data less than the precision of the results.

The PTA submission list is as follows:

2. Guess the number game

Guess the number game is to make game console randomly produce a positive integer within 100, the user enters a number to guess, you need to write a program automatically compare it with the randomly generated guessed number, and the hint is big ("Too big"), or small ("Toos Mall"), equal to guess. If guessed, the program is closed. The program also requires the number of statistical guesses, if 1 times to guess the number, the hint "bingo!" If the number is guessed within 3 times, it prompts "Lucky you!" If the number is more than 3 times but is within N (>3) (including nth), it prompts "good guess!" If you don't guess more than n times, prompt "Game over" and end the program. If the user enters a negative number before reaching n times, it also outputs "Game over" and ends the program.

The flowchart is as follows:

The source code is as follows:

 //2 Guess number game # include <stdio.h>int main (void) {int true_x = 0,try_max = 0,x = 0,try_num = 0;    scanf ("%d%d", &true_x,&try_max);     Prepare to enter the loop.    int flag = 0;    unsigned int i = 1;                for (; I <= Try_max; i++) {scanf ("%d", &x);            if (x < 0) {printf ("Game over");            flag = 1;        Break        } else if (x = = true_x) {break;}            else if (x > true_x) {try_num++;        if (I < Try_max) {printf ("Too big\n");}            } else {try_num++;        if (i > Try_max) {printf ("Too small\n");}     }}//judge the situation.        if (flag = = 0) {if (Try_num = = 0) {printf ("bingo!");}        else if (Try_num < 3) {printf ("Lucky you!");}        else if (Try_num < Try_max) {printf ("good guess!");}    else {printf ("Game over");} } return 0;  

I'm using a for loop because I've specified the number of loops, so I have to judge some conditions in the loop that need to jump out of the loop. Then, after the end of the loop, the loop is judged several times and the corresponding statements are output according to the changes in the values of some variables specified in the loop.

PTA Submission List:

3. Find Odd and

The subject requires the calculation of the odd number of a given series of positive integers.

The flowchart is as follows:

The source code is as follows:

//3 求奇数和#include <stdio.h>int main(void){    int x = 0,sum = 0;    //开始循环     sum = 0;    //sum再次赋初值0,因声明时已经初始化,所以可以省略。    while(1)    //无限循环,用break语句来结束循环,do-while语句肯定会运行一次循环体,若第一个值就输入非法,不符合题目要求。    {        scanf("%d",&x);                if(x > 0)        {            if(x%2 != 0)            {sum += x;}        }        else        {break;}    }    //循环结束,输出结果。     printf("%d",sum);    return 0; }

This problem is much simpler than the second question. Judge the data in an infinite loop and jump out of the loop and output the data after a certain condition. The output of the result must be aggregated at the end of the loop, and the problem does not require the output of intermediate data for each step.

The PTA submission list is as follows:

(iv) Mutual evaluation of blogs

My comments under the Li Xiaoxiao classmate Blog:

Big guy! Please take my knees, rapoter flowchart is too complicated, I really do not come out. And the big guy in the study Summary link also the program each time the variable value of the output with an output statement to debug the program, too professional.

My comments under the Xutianyu classmate blog:

Your blog format is very standard, but I think your experiment analysis can fill in some text makes the blog appear more full.

My comments under the Cheng classmate blog:

You finally processed the picture, before your pictures are hung up when the effect is really funny. Your source code can actually be written in markdown format instead of, or the combination of the two, it will be more beautiful.

My comments under the Yaoyuan classmate blog:
  
Old iron your white picture with a black background appears to be very clear that the picture and text appear, and that each step of your correct question is very clear and the steps are sufficient. old iron your ID is too cow! Have to serve!
  

My comments under the Zhaoxiaohui classmate blog:
  
Students you will be the source code and run the results are worth learning, but I think some single source code with the markdown format will be more clear.
  

I wish to comment on my classmates ' health and good luck.

C Language Programming sixth time job

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.