Question about function loop in C-language quiz games

Source: Internet
Author: User

Question about function loop in C-language quiz games

You may have written a quiz game when you are new to C. However, when writing a guessing function, you cannot avoid using loops.

When a function is nested in a loop, your score variable may be reset to the initial value in the function body. So how can this problem be solved?

In fact, it is very simple. You need to add an accumulation variable to the loop body so that the single-cycle scoring of the function body becomes the final total point through the cycle in the main function, then, you can determine your final points and wins or losses.

Below are some of the code I have written. please correct me!

1. Function body

Int compare (int x, int y) {int j = 0; // each cycle outside the function initializes the value of j if (x <3 & x> 0) {if (y-x = 0) {printf! ");} If (y-x = 1 | x-y = 1) {if (x> y) {printf (" You won this quiz! Add one point! "); J ++;} else {printf (" The computer won this time! Minus one point! "); J -- ;}} if (y-x = 2 | x-y = 2) {if (x> y) {printf ("The computer won this quiz! Minus one point! "); J --;} else {printf (" You won this quiz! Add one point! "); J ++ ;}}} else {printf (" You entered an error! \ N ") ;}return j; // the return value is initialized in each main function loop}

2. main Subject

For (I = 0; I <5; I ++) {printf ("\ n"); printf ("Please input your fist! "); Scanf (" % d ", & x); y = rand () % 3; printf (" % d \ n ", y ); ary [I] = compare (x, y); sum + = ary [I]; // The initialization of score variables is easily solved using the sum variable}

 

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.