C Language Programming sixth time-cycle structure (2)

Source: Internet
Author: User

(a) Experimental summary (i) the wrong question (i)

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 One:


Cause of Error:
There is no semicolon appended to the while statement
Workaround:
Add a semicolon after the while
Error message two:
Output does not match the requirements of the title
Cause of Error:
Looping setup Errors
Workaround:
The loop condition in the while is changed to
While (item >= EPS)
Error message three: Correct after correction still cannot output correctly
Error Reason: item = 1/n statement error, so item will only be equal to integer, and topic gives decimal
WORKAROUND: Change item = 1/n to item = 1.0/n
Error message four: There is still a small gap between the results of the calculation and the examples
Cause of error: Both EPS and s are defined at the beginning for the double type function, but are used with%f. This will result in a loss of precision and an error in the results.

(ii) Study summary

1. Statement while (1) and for (;;) What is the meaning? , how to ensure that this cycle can be performed properly?
These two statements all represent an infinite loop, and when used, ensure that the end condition is set to jump out of the loop, otherwise it will execute indefinitely. You can use break to jump out of the loop or exit (0) to end the program directly
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.
The number of cycles is known to be best used for statements, the number of loops is unknown, but the loop condition is clearly best used while entering the loop, the number of cycles is unknown, and the loop condition is unknown when entering the loop, it is better to use the Do While statement in the loop body explicitly.
Examples of suitable for types
PTA Cycle Structure Exercise One of the second question: statistics on the average student scores and pass number.
Source:

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

Because you know the number of students you enter (that is, the number of cycles), the For loop is used here
Examples of suitable while types
PTA Cycle Structure Exercise Two of the seventh question: looking for 250
Source

#include<stdio.h>int main(){int a,i=0;a=0;while(a < 250 || a>250){    scanf("%d",&a);    

It is better to use the while statement because you do not know the specific loop several times, but know the conditions for the loop to end.
Examples of the applicable do and statements
Circular structure Two of the sixth question: the number falling into the trap
Source

#include <stdio.h>int main(){int N,A,B,C,D,E,i=1,N2,flag = 1;scanf("%d",&N);do{   A=N%10;B=(N/10)%10;C=(N/100)%10;D=(N/1000)%10;E=N/10000;N2=(A+B+C+D+E)*3+1;if(N == N2){    flag += 1;} else{    N = N2;}printf("%d:%d\n",i,N2);i++;if(flag == 2){    break;}}while(1); return 0;

}

Here I quoted the code of Xu Zhengang classmate, because I was doing with while, read the code he wrote feel more convenient, first cycle to determine the loop condition, when the user input illegal characters more convenient to judge.
4. Run the following program, enter 1 to 10, what are the results? Why?
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 x,i=0,sum=0;double average; for(;;){    scanf("%d",&x);    if(x==-1)    break;    else    {        sum = sum + x;        i = i + 1;    } } average = (double)sum / i; printf("%lf",average); return 0;}

While statement

#include<stdio.h>int main(){int x,i=0,sum=0;double average; scanf("%d",&x);while(x >=0 ){    sum = sum + x;    i = i + 1;    scanf("%d",&x);} average = (double)sum / i; printf("%lf",average); return 0;}

Do While statement

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

Here the while and do while statements to pay attention to the transformation of conditions, while and do while both are satisfied with the conditional execution loop, so the most important to set the judgment condition as the result of >=0 to execute
Here I think that if you can use the infinite loop, either of which can be done well, if you can't think of it, I think the while loop is better, because the end condition is clear and does not need to be executed once to determine.
4. Run the following program, enter 1 to 10, what are the results? Why?
The first code runs the result

The result of the second code run

The first code I know is used to ask for an odd number of input numbers, but because a break is set in the loop, it causes the output to be 1 when it is odd to exit the loop.
The second code, because it is continue, will continue to execute the loop regardless of whether an even number is entered, and the final result is all of the input and that is 25

(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.
(2) Flowchart

(3) Source code

#include<stdio.h>#include<math.h>int main(){double eps,sum = 0.0,n = 1.0,a = 0.0;int i = 1;scanf("%lf",&eps);do    {        a = (1.0/i) * pow(-1,n+1);        sum = sum + a;        i = i + 3;        n++;    }while(fabs(a) > eps);printf("sum = %.6f",sum);return 0;}

(4) test data and operating results

(5) Experimental analysis

Error message one: Unable to output results
Cause of error: Loop condition set error causes dead loop, cannot output result
Workaround Set the loop condition to while (Fabs (a) > EPs);
Error message two: result error
Error reason: The Sum,n,a function does not have an initial value set
Workaround: Assign the above function at the beginning
(1) 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 ("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 a = 0,N = 0,i = 0,b = 0;scanf("%d%d",&a,&N);for(i = 1;i <= N;i++){    scanf("%d",&b);    if(b < 0 )    {        printf("Game Over");        break;    }    else if(b > a)    {        printf("Too big\n");    }    else if(b < a)    {        printf("Too small\n");    }    else if(a == b)    {        if(i == 1)        {            printf("Bingo!");            break;        }        else if(i <= 3 && i > 1)        {            printf("Lucky You!");            break;        }        else if(i > 3)        {            printf("Good Guess!");            break;        }        break;    }if(i >= N){printf("Game Over");break;}}return 0;}

(4) test data and operating results

(5) Experimental analysis
To distinguish the conditions of each output
Error message one: Incorrect output result
Error reason: Only one equals sign is used in the if condition, and one is assigned, two is equal
Workaround: Add an equal sign
(6) PTA Submission List

(1) Find odd and
The subject requires the calculation of the odd number of a given series of positive integers.
(2) Flowchart

(3) Source code

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

(4) test data and operating results

(5) Experimental analysis
This problem is relatively simple to pay attention to the cycle conditions and the conditions of judgment, basically no error
(6) PTA Submission List

(iv) Mutual evaluation of blogs

Liu Chansen
He Qiang
Hebotao

C Language Programming sixth time-cycle structure (2)

Related Article

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.