Classical, practical, and interesting programming examples in C/C ++ (1)

Source: Internet
Author: User
Tags acos ranges

1. Draw the cosine curve

Display 0 ~ with "*" on the screen ~ Cosine Function cos (x) curve with 360 degrees

* Problem analysis and Algorithm Design
If arrays are used in the program, this problem is very simple. However, if arrays cannot be used, the problem becomes difficult.
The key is that the cosine curve ranges from 0 ~ Within the range of 360 degrees, two vertices must be displayed in one row. For a general display, only output by row is allowed, you cannot return to the previous row. To obtain the image required in this article, you must output two "*" at a time in a row.
To obtain the two points of COS (X) on a row at the same time, the left and right symmetry of COS (X) is used. Define the Row Direction of the screen as X, and the column direction as Y, then 0 ~ 180-degree graphics and 180 ~ A 360-degree graph is symmetric between left and right. If the total width of the graph is 62 columns, the X rows are calculated from 0 ~ If the coordinate m of the Y point is 180 degrees, the 180 ~ The coordinates of the 360-degree y point should be 62-m. The arccosine function ACOs is used in the program to calculate the correspondence between coordinates (x, y.
The program compiled using this method is short and refined, reflecting certain skills.

* Program description and comment
# Include <stdio. h>
# Include <math. h>
Int main ()
{
Double Y;
Int X, M;
For (y = 1; y> =-1; y-= 0.1)/* Y is the column direction, the value ranges from 1 to-1, and the step size is 0.1 */
{
M = ACOs (y) * 10;/* calculate the radian M corresponding to Y, multiply by 10 as the image magnification */
For (x = 1; x <m; X ++) printf ("");
Printf ("*");/* control the number * on the left side of the print */
For (; x <62-m; X ++) printf ("");
Printf ("*/N");/* control printing the symmetric right side of the same line */
}

Return 0;
}

* Questions
How to use "*" to display 0 ~ The sin (x) curve with 360 degrees.

0 ~ 360 degrees cos (x) curve and linear f (x) = 45 * (Y-1) + 31 superposition graphics. Cos (X) is represented by "*", f (x) is represented by "+", and f (x) is used to represent the intersection of two images.

2. Draw cosine curves and straight lines

* Problem analysis and Algorithm Design
This question can be modified on the basis of the above question. The key to drawing superposition is to correctly determine the positional relationship between the two figures after calculating the coordinates of the column direction of the two figures in the same row respectively. Therefore, you can determine the intersection of the image and then control the printing of two different images.

* Program comments and descriptions
# Include <stdio. h>
# Include <math. h>
Int main ()
{
Double Y;
Int X, M, N, YY;
For (yy = 0; YY <= 20; YY ++)/* calculate the first y coordinate and print the image in a row */
{
Y = 0.1 * YY;/* Y: coordinates of the line of the screen */
M = ACOs (1-y) * 10;/* M: The Screen column coordinate corresponding to the Y point on the CoS (x) curve */
N = 45 * (Y-1) + 31;/* n: the column coordinate corresponding to the Y point on the line */
For (x = 0; x <= 62; X ++)/* X: coordinates of the orientation of the screen column */
If (x = M & X = N) printf ("+");/* print "+ "*/
Else if (x = N) printf ("+");/* print the line chart when there is no intersection */
Else if (x = M | x = 62-m) printf ("*");/* print the CoS (x) image when there is no intersection */
Else printf ("");/* print spaces in other cases */
Printf ("/N ");
}

Return 0;
}

* Questions
How to display sin (x) curves and cos (x) curves simultaneously.

3. Draw circles

Draw a hollow circle with "*" on the screen

* Problem analysis and Algorithm Design
The print circle can use the left and right symmetry of the image. According to the equation of the circle:
R * r = x * x + y * y
The correspondence between each row and column on the circle can be calculated.

* Program description and comment
# Include <stdio. h>
# Include <math. h>
Int main ()
{
Double Y;
Int X, M;
For (y = 10; y> =-10; y -)
{
M = 2.5 * SQRT (100-y * Y);/* calculate the column coordinate M corresponding to row Y. 2.5 is the screen aspect ratio adjustment coefficient because the screen
The line spacing is greater than the column spacing. If you do not adjust it, it will be an ellipse */
For (x = 1; x <30-m; X ++) printf ("");/* blank control on the left side of the image */
Printf ("*");/* left side of the circle */
For (; x <30 + m; X ++) printf ("");/* controls the hollow part of the image */
Printf ("*/N");/* right side of the circle */
}
Return 0;
}

* Questions
Implement overlapping display of the graph and the circle of Function Y = x2

4. Singer Grand Prix

In the singer Grand Prix, 10 judges scored the contestants with a score of 1 ~ 100 points. The final score is: remove the average value of one highest score and the other eight scores after one lowest score. Compile a program for implementation.

* Problem analysis and Algorithm Design
The algorithm for this problem is very simple, but pay attention to how to assign values to the variables that determine the maximum and minimum values in the program.
* Program description and comment
# Include <stdio. h>
Int main ()
{
Int integer, I, Max, Min, sum;
Max =-32768;/* assume that the current maximum value Max is the minimum value of the C Integer Number */
Min = 32767;/* First, assume that the current min value is the maximum value of the C Integer Number */
Sum = 0;/* set the initial values of sum and variable to 0 */
For (I = 1; I <= 10; I ++)
{
Printf ("input Number % d =", I );
Scanf ("% d", & integer);/* enter the score of the judge */
Sum + = integer;/* calculate the total score */
If (integer> MAX) max = integer;/* filter the highest score by comparison */
If (integer <min) min = integer;/* filter the shard points by comparison */
}
Printf ("canceled Max score: % d/ncanceled min score: % d/N", Max, min );
Printf ("average score: % d/N", (Sum-max-min)/8);/* output result */
}

* Running result
Input number1 = 90
Input number2 = 91
Input Number3 = 93
Input number4 = 94
Input number5 = 90
Input number6 = 99
Input number7 = 97
Input number8 = 92
Input number9 = 91
Input number10 = 95
Canceled Max score: 99
Canceled min score: 90
Average score: 92

* Questions
The subject conditions remain unchanged, but the evaluation of the judges should be considered at the same time, that is, the most equitable score should be found among the 10 judges (that is, the lowest score is returned to the average score) how should the procedure be implemented for the judges who are the most unfair (that is, the biggest gap with the average score?

5. Calculate the maximum number

Q: What is the maximum three-digit number of an appointment in 555555?

* Problem analysis and Algorithm Design
According to the definition of an appointment, for an integer N, except for 1 and itself, any number that can divide N is an appointment of N. Therefore, the simplest method is to remove N with all the numbers between 2 to the N-1, and we can find all the approximate numbers of N. To obtain the maximum three-digit number of an appointment, the value range of this question can be between 100 and 999.
* Program description and comment
# Include <stdio. h>
Int main ()
{
Long I;
Int J;
Printf ("Please input number :");
Scanf ("% lD", & I );
For (j = 999; j> = 100; j -)
If (I % J = 0)
{
Printf ("the Max Factor with 3 digits in % LD is: % d,/N", I, j );
Break;
}
}

* Running result
Input: 555555
Output: The Max Factor with 3 digits in 555555 is: 777

6. The ending number of the high power

Calculate the last three digits of 13 to the power of 13

* Problem analysis and Algorithm Design
The most direct way to solve this question is to cut the last three digits from the power of 13 to the power of 13.
However, due to the limited Integer Range that the computer can represent, it is impossible to use this "correct" algorithm to obtain the correct result. In fact, the question only requires the last three values, and there is no need for a complete result of 13 to the power of 13.
The law of multiplication finds that the last three values of the product are only related to the first three values of the multiplier and the last three digits of the multiplier, and are irrelevant to the high positions of the multiplier and the multiplier. Using this rule can greatly simplify the program.
* Program description and comment
# Include <stdio. h>
Int main ()
{
Int I, X, Y, last = 1;/* the last three digits of the product in the process of finding the power of Y in the last variable */
Printf ("input X and Y (x ** y ):");
Scanf ("% d ** % d", & X, & Y );
For (I = 1; I <= y; I ++)/* x */
Last = last * x % 1000;/* modulo the last three digits after the last X, that is, the last three digits of the product */
Printf ("the last 3 digits of % d ** % d is: % d/N", X, Y, last % 1000);/* print the result */
}

* Running result
Input X and Y (x ** y): 13 ** 13
The last 3 digits of 13 ** 13 is: 253
Input X and Y (x ** y): 13 ** 20
The last 3 digits of 13 ** 20 is: 801

7. Number of zero factorial tails

100! How many zeros does the ending number have?

 

* Problem analysis and Algorithm Design
Imagine: first obtain 100! And then count the number of zeros at the end. As a matter of fact, it is impossible for a computer to represent a limited range of integers.
To solve this problem, we must first analyze it in mathematics at 100! The condition that produces zero at the end of the result value. It is not hard to see: if an integer contains a factor 5, it will inevitably be 100! Generate a zero value. Therefore, the question is how many factors 5 are contained in the 100 integers from 1 to 100. If integer N can be divisible by 25, N contains 2 factors 5. If integer N can be divisible by 5, N contains 1 Factor 5.
* Program description and comment
# Include <stdio. h>
Int main ()
{
Int A, Count = 0;
For (A = 5; A <= 100; A + = 5) // The cycle starts from 5 and takes a multiple of 5 as the step.
{
+ + Count; // if it is a multiple of 5, add 1 to the counter
If (! (A % 25) + + count; // if it is a multiple of 25, add 1 to the counter
}
Printf ("the number of 0 in the end of 100! Is: % d./N ", count); // print the result
Return 0;
}

* Running result
The number of 0 in the end of 100! Is: 24.

* Further Discussion

The solution to this question is correct, but there are obvious disadvantages. The method used in the program to determine the number of factors 5 contained in integer N is related to the 100 in the program. If the 100 in the question is changed to 1000, it is necessary to modify the algorithm used to calculate the number of factors 5 in the program.

* Questions

Modify the number algorithm for Factor 5 in the program so that the program can find any n! Number of zeros at the end.

8. How much do I know about the borrowing scheme?

James has five new books to lend to three children, A, B, and C. If each person can only borrow one book at a time, how many different ways can James borrow?

* Problem analysis and Algorithm Design
This problem is actually a problem of arrangement, that is, to obtain the total number of three methods for arrangement from five. First, numbers the five books from 1 to 5, and then uses the exhaustive method. Assume that three of them borrow one of these five books. When the numbers of the books borrowed by the three are different, it is a way to borrow the question.
* Program description and comment
Int main ()
{
Int A, B, C, Count = 0;
Printf ("there are diffrent methods for XM to distribute books to 3 readers:/N ");
For (A = 1; A <= 5; A ++)/* list all the situations in which the first person borrows one of the five books */
For (B = 1; B <= 5; B ++)/* list all the situations in which the second person borrowed one of the five books */
For (C = 1;! = B & C <= 5; C ++)/* when two people borrow different books, the third party borrows 5 books.
All the situations of the first version */
If (C! = A & C! = B)/* determine whether the third party is different from the books borrowed by the first two */
Printf (count % 8? "% 2D: % d, % d, % d": "% 2D: % d, % d, % d/N", ++ count, A, B, c );
/* Print the possible borrow Method */
}

* Running result
There are diffrent methods for XM to distribute books to 3 readers:
1:, 3 2:, 4 3:, 5 4:, 2 5:, 4
6:, 5 7:, 2 8:, 3 9:, 5 10, 5, 2




31: 3, 4, 1 32: 3, 4, 2 33: 3, 4, 5 34: 3, 5, 1 35: 3, 5, 2
36: 3, 5, 4 37: 4, 1, 2 38: 4, 1, 3 39: 4, 1, 5 40: 4, 2, 1
41: 4, 2, 3 42: 4, 2 43: 4, 3, 1 44: 4, 3, 2 45: 4, 3, 5
46: 4, 5, 1 47: 4, 5, 2 48: 4, 5, 3 49: 5, 1, 2 50: 5, 1, 3
51: 5, 1, 4 52: 5, 2, 1 53: 5, 2, 3 54: 5, 2, 4 55: 5, 3, 1
56: 5, 3, 2 57: 5, 3, 4 58: 5, 4, 1 59: 5, 4, 2 60: 5, 4, 3

9. Yang Hui triangle

Display Yang Hui triangle on screen

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
......................................

* Problem analysis and Algorithm Design
The number in the Yang Hui triangle is the coefficient of the (x + y) Power of the Npower expansion. This question is representative in programming. There are many ways to solve it. Here we only provide one.
Starting from the characteristics of the Yang Hui triangle, we can summarize the following:
1) the nth row has n + 1 values (set the starting behavior to 0th rows)
2) for the J value of row N: (n> = 2)
When j = 1 or J = n + 1: The value is 1.
J! = 1 and J! = N + 1: The value is the N-1 number of the J-1 line and the J value of the N-1 line
Sum
Refining these features into mathematical formulas can be expressed:
1 x = 1 or X = n + 1
C (x, y) =
C (x-1, Y-1) + C (x-1, Y) Other

This procedure should be based on the above recursive mathematical expressions.
* Program description and comment
# Include <stdio. h>
Int main ()
{
Int I, j, n = 13;
Printf ("n = ");
While (n> 12)
Scanf ("% d", & N);/* control the input of correct values to ensure that the displayed images are correct */
For (I = 0; I <= N; I ++)/* controls the output of N rows */
{
For (j-0; j <24-2 * I; j ++) printf ("");/* control the spaces before the output line I */
For (j = 1; j <I + 2; j ++) printf ("% 4D", C (I, j )); /* output the J value of row I */
Printf ("/N ");
}
}

Void int C (int x, int y)/* calculate the value of column Y in row X of the Yang Hui triangle */
{
Int Z;
If (y = 1) | (y = x + 1) return 1;/* if it is row 1st or column x + 1, output 1 */
Z = C (x-1, Y-1) + C (x-1, Y);/* otherwise, the value is the sum of the values of the Y-1 column and Y column in the first row */
Return Z;
}

* Questions
A self-designed method for realizing the Yang Hui triangle

10. Digital Conversion

Convert any integer to binary

* Problem analysis and Algorithm Design
There are many ways to convert a decimal integer to a binary value. The implementation method described here utilizes the features that the C language can perform bitwise operations. For C language, an integer is stored in binary form in the computer, so it is not necessary to convert an integer to binary form after a series of operations, you only need to output the binary representation of the integer in the memory.
* Program description and comment
# Include <stdio. h>
Void printb (INT, INT );
Int main ()
{
Int X; printf ("input number :");
Scanf ("% d", & X );
Printf ("number of decimal form: % d/N", X );
Printf ("It's binary form :");
Printb (x, sizeof (INT) * 8);/* X: integer sizeof (INT): the number of bytes occupied by the int type in the memory
Sizeof (INT) * 8: number of digits corresponding to the int type */
Putchar ('/N ');
}

Void printb (int x, int N)
{
If (n> 0)
{
Putchar ('0' + (unsigned) (X & (1 <(n-1)> (n-1);/* output N-bit */
Printb (x, n-1);/* is called, and the last n-1 bit of X is output */
}
}

* Running result
Input: 8
Output:
Number of decimal form: 8
It's bunary form: 0000000000001000
Input:-8
Output: number of decimal form:-8
It's binary form: 1111111111111000
Input: 32767
Output: number of decimal form: 32767
It's binary form: 0111111111111111
Input:-32768.
Output: number of decimal form:-32768
It's binary form: 1000000000000000
Input: 128
Output: number of decimal form: 128
It's binary form: 0000000010000000

* Further Discussion
Taking full advantage of the features that the C language can perform operations on counterpoint, you can write many programs that are not easy to write or even impossible to write in other advanced languages. Bit operations are a major feature of the C language, and should be well mastered in the Process of deep learning the C language.
The bit operation method used in the program is not the best, or you do not need to perform recursive operations. You can optimize the program on your own.

* Questions
Converts any positive integer to a quartile or octal number.

 

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.