C Language Programming sixth time-cycle structure (2)

Source: Internet
Author: User

(a) Correct the wrong question

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
source program (with the wrong program)

#include<stdio.h>int main(){    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;}

Error One:
Error reason: There is no semicolon after the while statement


Correction method: Add a ";" After the while (Item < EPS)

Compile without errors after correcting the errors

Input data validation

Program error

Error Two:
Error reason: Eighth line input statement has a problem, should not use%f

Correction method: Change%f to%LF

Error three
Error reason: The operation in line 13th is an integer operation and cannot appear as a real number


Correction method: Change "item = 1/n" In "1" to "1.0"

After correction, input data, the program is still wrong

Error Four
Error reason: Output statement has a problem,%f error


Correction method: Change%f to%LF

Error Five
Error reason: Loop statement has error, while statement inside parenthesis is wrong

How to correct: change "<" in "while (Item > EPS)" to ">"

Validation of corrected program input data

Attach the corrected procedure:

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

1. Statement while (1) and for (;;) What is the meaning? , how to ensure that this cycle can be performed properly?
A: Two statements are circular statements, and all are infinite loops, which is what we call the Dead loop, which applies to loops that do not know the number of times the loop should run. while () in the parentheses of the judge is whether the condition in parentheses is true, as long as the brackets are any non-0 values, are judged true, so not necessarily 1, other non-0 values can be, such as: 1,-5, etc. can be. The For loop is judged based on the three expressions in parentheses of the for (;;), the second expression is the condition of the loop, and if the second expression is empty, the condition of the loop stop is missing and the loop statement is infinite.
To ensure that this loop executes properly, it must be guaranteed that the condition is "1", which is true, that the statement itself cannot have an error, and that no loop control statements, such as a break statement, are present.

2. In general, when designing a looping structure, it is possible to use the for, while, does while three statements, and three statements can be converted to each other, but in some specific cases, we should first select some kind of statement to quickly implement the loop design. If the following conditions are true:
(1) Number of cycles known
(2) The number of cycles is unknown, but the cyclic conditions are clear when entering the cycle
(3) 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
For the above three cases, what is the use of the loop statement to achieve better? For each case, use the topics in the two-cycle structure work we have completed to illustrate.

A: (1) It is better to use a for statement if the loop statement is known, because the For statement contains an explicit statement that stops the loop. such as PTA cycle in the first job, to find one of the odd points in the sequence of the first n and this problem, it is easier to use for the statement, clear the number of cycles, select an initial value, clear the end of the conditions, you can come to an answer.
(2) The number of cycles is unknown, but the loop condition is clear when entering the loop, this situation is better using the while statement, because the number of cycles is unknown, but some conditions are known, you can use the loop. If he is afraid of the second operation of the cycle, Han Xin soldiers of the problem is to use the while statement, using the first loop in the form of judgment, the number of cycles of the problem we do not have to calculate the situation does not know, but the conditions given by the topic can let us write the loop Stop statement, so the use of the while statement is better.
(3) The number of cycles is unknown, and the cycle conditions in the loop into the unknown, need to be clear in the loop body, such a situation we generally use the Do while statement. such as PTA cycle in the second job fall into the number of traps, we have the number of cycles and the condition of the loop stop is not clear, do While loop execution mode is to first enter the loop body to execute a loop body, and then judge whether the cycle condition is set up, so that using the loop body we can make the loop execution down To meet the requirements of the topic.

3. The following questions: Enter a batch of student scores, ending with 1 to calculate the student's average score.
It is required to use the For statement, while statement, do While statement three loop statement implementation, and explain which form you think is more appropriate?

(1) If a For statement is used, the program is as follows:

#include<stdio.h>int main(void){int grade=0,sum=0,i=0;double average=0.0;for(;;) {scanf("%d",&grade);if(grade!=-1){sum = sum +grade;i++;}else if(grade==-1){break;}}average = sum / i;printf("%f",average);return 0;}

(2) If using the while statement, the program is as follows:

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

(3) If you use the Do While statement, the program is as follows:

#include<stdio.h>int main(void){int grade=0,sum=0,i=0;double average=0.0;i=0;do{scanf("%d",&grade);sum = sum + grade;i++;        }while(grade!=-1) ;average = (sum+1) / (double)(i-1);printf("%f",average);return 0;}

(4) Infinite loop. The procedure is as follows:

#include<stdio.h>int main(void){int n = 0,sum = 0,count = 0;    for(;;)                               {    scanf("%d",&n);                   if(n < 0)                        {        break;    }    else    {        sum += n;    count++;    }    }if(count == 0)   {    count++;}printf("average = %.1f\n",(double)sum / count);return 0;}

From the code point of view, the while loop and the Do While loop are concise, but for loops and infinite loops I think it's more understandable, in general I think the while statement is more appropriate because the number of students is unknown at the time of input, so the For loop is not very good, and when we enter the finished, The loop condition is clear when entering the loop, so it is better than the Do While loop, compared to the tedious loop, while loop is relatively concise, so while loop is better.

4. Run the following program, enter 1 to 10, what are the results? Why?

Running the program (1) results such as:

Running the program (2) results such as:

Cause: Two program result output is obviously different, the difference is that a break statement out of the loop, the other is continue. If the content behind the IF statement is a break statement, that is, to jump out of the loop, if the loop is nested form, when the loop executes the For statement, when the break statement, the break statement will jump out of his nearest loop, not the next loop, but the continue statement is different, When the loop executes the For statement, the continue statement is reached, and the continue statement skips over the continue and executes the judgment of the nearest loop. So this problem, with the break statement is obviously not enough to meet the requirements, you should use the Continue statement.

(iii) Experimental summary

1. Simple staggered sequence parts and problems for a given precision
(1) Title
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.
(2) Flowchart

(3) Source code

#include<stdio.h>#include<math.h>int main(){int n = 1;double eps,a = 1.0,S = 1.0,sum = 0.0;scanf("%lf",&eps);do{    a = 1.0 / (S* pow(-1,n+1));    S = S + 3 ;    sum = sum + a;    

(4) Experimental analysis
Issue: Output 0.0000000
WORKAROUND: Force the result of the calculation into a double type

(5) PTA Submission List

2. Guess the number game
(1) Title
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 ("Too small"), 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.
(2) Flowchart

(3) Source code

#include<stdio.h>int main(){int M,N,n = 0,math;scanf("%d%d",&M,&N);do{       n++;    scanf("%d",&math);    if(math<0)    {        printf("Game Over");        break;    }    else if(n>N)    {        printf("Game Over");        break;    }    else if(math==M)    {        if(n==1)        {            printf("Bingo!");            break;        }        else if(n==2||n==3)        {            printf("Lucky You!");            break;        }        else        {            printf("Good Guess!");            break;        }    }    else if(math<M)    {        printf("Too small\n");    }    else if(math>M)    {        printf("Too big\n");    }   }while(1);return 0;}

(4) Experimental analysis
Problem: After entering the correct answer, still output gameover
Workaround: Add exit Bilgo (0)

(5) PTA Submission List

3. Finding odd numbers and problems
(1) Title
The subject requires the calculation of the odd number of a given series of positive integers.
(2) Flowchart

(3) Source code

#include <stdio.h>int main(){int N,sum=0;    while(1)    {        scanf("%d",&N);        if(N%2!=0&&N>0)        {            sum+=N;        }        if(N<=0)        {            break;        }    }printf("%d",sum);return 0;}

(4) Experimental analysis
Question: After entering-1,-1 also if the calculation
Workaround: Do not exit the loop in time, subtract the loop variable one time,

(5) PTA Submission List

(iv) Mutual evaluation of blogs

Li Xiaoxiao http://www.cnblogs.com/Reloaded/p/7825734.html
Liu Dream Awake
Tengwenqing

C Language Programming sixth time-cycle structure (2)

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.