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 message 1:

Cause of Error:
There is a semicolon after the while statement when executing a Do While loop.
Correction Method:
Add a semicolon after the while statement.
The compilation is correct after the modification.

Operation Result:

Found the running result is incorrect, modify the program.
Error message 2:

Cause of Error:
When you define a variable, the EPS is of type double, so the input is not input%f.
Correction Method:
Change the%f to%LF.
Operation Result:

Continue to modify the program if you find that the result is not working.
Error message 3:

Cause of Error:
According to the requirements of the topic, it should not be item

1. Statement while (1) and for (;;) What is the meaning? , how to ensure that this cycle can be performed properly?
while () is in parentheses to determine whether the condition is true, while (1) means that the condition is always true, so while (1) is an infinite loop. There are three statements in the For Loop, the first statement is an assignment statement, executes only once, the second statement is the judgment statement, whether the statement is true or false, and the third statement is generally to add 1 to the assignment statement. But for (;;) The three statements are empty, which indicates that the judging condition is always true, so it is also an infinite loop.
To ensure that this cycle can be normal, you can meet the conditions of the problem, add a break statement, let the program out, the end of the program.
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.
(1) The number of cycles is known, you want to quickly realize the loop design, you can prefer the for statement.
For example: The first question in the loop structure (1) is to find one of the odd points of a sequence of first n items and is convenient with a for statement.

# include <stdio.h>int main (void){    int N,i;    double sum;    scanf("%d",&N);    for(i=1,sum=0;i<=N;i++)    {    sum=sum+1.0/(2*i-1);    }    printf("sum = %.6f",sum);    return 0;}

(2) The number of cycles is unknown, but the cyclic conditions are clear when entering the loop, and the loop design can be realized quickly by using the while statement.
For example: The first problem in a cyclic structure (2) is to find a simple staggered sequence part of a given precision, and a while statement is appropriate.

# include <stdio.h># include <math.h>int main (){    int flag,d;    double eps,item,sum;    item=1,flag=1,sum=0,d=1;    scanf("%lf",&eps);    if(item<=eps)    {      sum=1;    }    while(fabs(item)>eps)    {        item=flag*1.0/d;        sum=sum+item;        d=d+3;        flag=-flag;    }    printf("sum = %.6f",sum);    return 0;}

(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, with a do while statement.
For example: The third question in the loop structure (2) is odd and.

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

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?
For statement:

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

While statement:

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

Do While statement:

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

I think it is more appropriate to write with a while statement because the loop number is unknown and the loop condition is clear when entering the loop.
4. Run the following program, enter 1 to 10, what are the results? Why?
(1)

#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;}

Loop Result:

(2)

#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;}

Loop Result:

The running results show (1) in S=1, (2) in s=25. The difference between the two reasons is: (1) in the N%2==0 statement followed by the break statement, when the input n=2, the program will jump directly, so s is equal to 1 of the previous step. and (2) in the n%2==0 followed by the continue statement, the continue statement is that only jump out of this step, and then proceed to the next step.
(iii) Experimental summary

This experiment summarizes 1, 2 and 3 questions in the cycle structure (2).
1. The simple staggered sequence part of the given precision and

(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 flag,d;    double eps,item,sum;    item=1,flag=1,sum=0,d=1;    scanf("%lf",&eps);    if(item<=eps)    {      sum=1;    }    while(fabs(item)>eps)    {        item=flag*1.0/d;        sum=sum+item;        d=d+3;        flag=-flag;    }    printf("sum = %.6f",sum);    return 0; }

(4) Experimental analysis
Problem:
When the job was submitted on the PTA, some of the correctness occurred.
Reason:
There is no consideration of what happens when the first item entered is less than or equal to the given precision EPs.
Workaround:
Ask the classmate to revise the procedure.
(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 num,N,i,n;i = 1;scanf("%d %d",&num,&N);do{scanf("%d",&n);if(n < 0){printf("Game Over");break;}else if(n == num && i <= N){if(i == 1){printf("Bingo!");break;}else if(i <= 3){printf("Lucky You!");break;}else if(i > 3 && i <= N){printf("Good Guess!");break;}}else if(i > N){printf("Game Over");break;}else if(n > num){printf("Too big\n");}else if(n < num){printf("Too small\n");  }i++;}while(num != n);return 0;}

(4) Experimental analysis
Question 1:
Run time can only draw a set of data, is too big or too small, can not guess the number of times.
Reason:
Just beginning with the while statement, there is no logical relationship.
Workaround:
Ask the classmate, finally changed to do while statement, the result is correct.
(5) PTA Submission List



3. Find Odd and
(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;    sum=0;    do    {            scanf("%d",&n);        if(n<0)        {            break;        }        else if(n%2==1)        {            sum=sum+n;        }    }while(n>0);    printf("%d",sum);    return 0;}

(4) Experimental analysis
Problem:
It is not correct to write with a while statement or for statement.
Reason:
Because the program is not known for the number of times it enters the loop, and the loop condition is not very clear.
Workaround:
Changed to a do while statement.
(5) PTA Submission List


(iv) Mutual evaluation of blogs

Each student reviews at least three other students ' blog assignments, listing the blog addresses you commented on in turn. For the students on your blog homework questions, should be actively answered, the existence of errors should be corrected in time. We hope that we can learn from each other in the process of mutual evaluation and make progress together.
1. Wang Yingdan: http://www.cnblogs.com/windsky-1999/p/7838107.html
Wang Yingdan classmate, in the correct problem in the thinking clear, can let a person at a glance at where the mistake.
Learn to summarize the second question if you can give examples of the source code will be better.
The whole idea of work is clear and worth learning.
2.luckyyou:http://www.cnblogs.com/lyfrrs/p/7854183.html
In the wrong question, the idea is clear.
In the second part of the study summary, if you can write out the source code of the example, it might be better.
The source code of the experiment analysis is best to write in markdown format, do not intercept screen.
3. Cheng: http://www.cnblogs.com/8426224ll/p/7847221.html
In the wrong problem, the idea is clear, where there are errors, but also made a mark.
In the experiment analysis, the error source program can be compared with the correct source program, which is worth studying.
PTA Submission List of errors in the overall less, worth learning.

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.