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

Cause of Error:
There is no semicolon appended to the while statement
Workaround:
Add a semicolon after a while statement
Error message two:

Cause of Error:
Loop condition Set Error
Workaround:
The loop condition in the while is changed to
While (item >= EPS)
Error message Three:

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 gap between the calculation results and 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.
Workaround:%f Change to%LF
Ultimately correct

(ii) Study summary
1. Statement while (1) and for (;;) What is the meaning? , how to ensure that this cycle can be performed properly?
A: All two are infinite loops. If you want to run normally, you have to be able to end the loop, you can use break 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.
A: The (1) type is the best for statement.
Example: 2017 loop structure (1) 7-1 find one of the odd points sequence the first n items and

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

Because the number of known loops is input, it is known, so the For loop is optimal.

The first (2) is optimal with the while statement.
Example: 2017 cycle structure (2) 7-7 find 250

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

Because the loop condition is clear when entering the loop, it is to find 250.

The first (3) is optimal with a do while statement.
Example: 2017 loop structure (2) 7-3 to find odd and

int main(){    int n = 0, sum = 0;    do    {        scanf("%d", &n);        if (n % 2 == 1)         sum += n;    }    while (n > 0);    printf("%d\n", sum);    return 0;}

Because the number of cycles is unknown and the loop condition is unknown when entering the loop, it can be understood in the loop body.

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

I think the while statement is better because the end condition is clear.

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

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

The results were
(1)
(2)
(1) When input 1 o'clock, 1%2=1, loop, input 2 o'clock 2%2=0break, jump out of the loop output S=1, end the program.
The first (2) Continue is that when an even number is entered, the next s = S + n is not executed, and the single loop continues, so the program computes the odd number of inputs and.

(iii) (experimental summary)

    1. (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) Experimental analysis
At first, I didn't know much about it, but I didn't understand how to control the end of the loop after seeing the problem.
(5) PTA Submission List

    1. (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) Experimental analysis
Each step is not very complicated, but it is very complicated to look at it together, so we need to figure out every step.
(5) PTA Submission List

    1. (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; }

(5) PTA Submission List

(iv) Mutual evaluation of blogs
Http://www.cnblogs.com/moying456/p/7859207.html
Http://www.cnblogs.com/he111923/p/7840814.html
Http://www.cnblogs.com/ying-7/p/7857820.html

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.