Tan Haoqiang C programming fourth edition answers

Only some answers that require programming are given, using the book of Teacher Tan Haoqiang:

This article is continuously being updated...

For some notes in the C programming textbook, see: C programming notes

my directory

The first unit

6. Write a c program, input three values ​​of a, b, and c, and output the largest of them
#include<stdio.h>
int main()
{
	int a, b, c,d;
	int max(int x, int y, int z);
	printf("enter three number:");
	scanf_s("%d,%d,%d", &a, &b, &c);
	d = max(a, b, c);
	printf("max=%d\n", d);
	return 0;

}
int max(int x, int y, int z)
{
	int max;
	max = x;
	if (max < y)
		max = y;
	if(max<z) 
		max = z;
	return max;

}

Using the c++ library function can only compare two numbers max(), and only two numbers can be placed in min(). Therefore, you can use the max(max(a,b),c) method to compare three numbers
https://wenku.baidu.com/view/f34993086137ee06eef91811.html?rec_flag=default&sxts=1543935291260

#include<stdio.h>   //预处理
#include<algorithm>  
using namespace std;    //使用命名空间std
int main()    //主函数首部
{         //函数体开始
	int x, y, z, max_num;     //定义变量
	printf("Enter three numbers:");
	scanf_s("%d,%d,%d", &x, &y, &z);
	max_num = max(x, y);
	printf("最大值是:%d\n", max_num);
	return 0;
}    //函数结束

Second unit

2.1 What is an algorithm, try to find 2 examples from daily life, and describe their algorithms

The book gives:
program = algorithm + data structure program = algorithm + data structureprogram=algorithm+Data structure
Algorithm isthe operationthe stepsthat require the computer to operate. In a broad sense:the methods and steps taken to solve a problem are"algorithms". More specifically: the data structure is the processing/operation object, the language is the tool, and the algorithm is the soul.
Example 1: Buying a train ticket to go home during the Chinese New Year, you need to pack your luggage first, go to the station, book the ticket, pay, get the ticket, get on the train, there are still many processes here, such as changing trains, etc., to get home. The algorithm is this series of steps, and the optimization of the algorithm is aimed at a certain direction, such as getting home the fastest and most economically, and adopting some means to achieve this goal.
Example 2: Cooking; you need to buy vegetables first, wash vegetables, cut vegetables, cook a lot of processes, and finally put condiments.
So from the above, we can see that the process is actually an algorithm, so it is
insert image description here
the source of the picture:Ribbon What is an algorithm?
The blogger wrote it in detail, I suggest you take a look

2.2 What is a structured algorithm and why should a structured algorithm be advocated

Algorithms composed of basic structures are called "structured" algorithms, and the basic structures are three basic structures: sequence structure, selection structure and loop structure.
Structured algorithms can make a complex problem more simplified and easy to read through the basic structure, and at the same time, it is also easy to modify, simplifying complex problems, making programming easier, and improving code maintenance and readability (the latter sentence is from Baidu Encyclopedia)

2.6 Use pseudocode to express the algorithm of each question in question 4

Here I will not write pseudo code, directly on the code
(1)

third unit

3.1 If the annual growth rate of my country's GNP is 9%, calculate the percentage increase of my country's GNP 10 years from now. The calculation formula is:

p = ( 1 + r ) n p=(1+r)^n p=(1+r)n

#include <stdio.h>
#include <math.h>

int main()
{
   /* 计算增长百分比 */
   float r=0.09,p;
   int n=10;
   p=pow(1+r,n);
	printf("%.3f",p);

   return 0;
}
3.2 Calculation of deposit interest. If you have 1,000 yuan and want to save it for 5 years, there are five ways.
The results obtained by each method are:
#include <stdio.h>
#include <math.h>

int main()
{
   /* 本息和 */
   float p0,p1,p2,p3,p4,r0=0.0072,r1=0.0414,r2=0.0468,r3=0.0540,r4=0.0585;
   int p=1000;
	
	p0=p*(1+5*r4);    //一次存五年
	p1=p*(1+2*r2)*(1+3*r3);  //先存2年再存3年
	p2=p*(1+3*r3)*(1+2*r2);   //先存两年后存3年
	p3=p*pow(1+r1,5);   //连续存5年,一次一年
	p4=p*pow(1+r0/4.0,4*5);
   printf("p0=%f\n,p1=%f\n,p2=%f\n,p3=%f\n,p4=%f",p0,p1,p2,p3,p4);

   return 0;
}

p0=1292.500000
,p1=1270.763062
,p2=1270.763184
,p3=1224.863770
,p4=1036.622314
It can be seen that depositing for 5 years will be more profitable

Replenish:
  • There is a comma before the above output, because I wrote a comma between the two variables in printf() (using python), so if there is no comma, for C language, there is no need between the two parameters Any symbol (do not use spaces, otherwise spaces will be output directly, C starts from the left of the output, and starts to replace when encountering the format declaration symbol %, and then continues to output one by one until the next %).
  • Change the above deposit to 10,000 or 100,000, and it is still the most fixed deposit for 5 years, and the smallest current deposit (because banks encourage fixed deposits)
3.3 How many months to pay off the loan.
#include <stdio.h>
#include <math.h>

int main()
{
   int d=300000,p=6000;
	float r=0.01,m,n,l;
	
	m=log10(p/(p-d*r))/log10(1+r);
	printf("一共需要%.1f还清",m);

   return 0;
}

A total of 69.7 needs to be paid off

Replenish:

69.7*6000=418200 is close to 420,000, a loan of 300,000 has to be repaid in six years, a total of 420,000, a bank that eats people. . . .

3.4 Analyze the following program
#include <stdio.h>
#include <math.h>

int main()
{ char c1,c2;
 c1=97;
 c2=98;
 printf("c1=%c,c2=%c\n",c1,c2);
 printf("c1=%d,c2=%d\n",c1,c2);
   
 return 0;
}

(1) The result of running
c1=a, c2=b
c1=97, c2=98

analyze:

This is a type conversion problem during assignment or output. First define/declare that c1 and c2 are character types, and only one byte of memory is allocated. The characters corresponding to the ASCII codes (P337) of 97 and 98 are a and b. So the first output is character output (output mode on page P97), which is a, b. The second output is an integer output, which is 97, 98.

(2)
After writing a lot with great difficulty, it was not automatically saved for some reason, and the wasted hours were really desperate. . . . . . . Tucao CSDN! (After all, I posted a picture, and then deleted the original picture, where can I find the original picture?!)
Forget it, write it again. Not all of them are written.
insert image description here

3.5 Input data with the following scanf function,. . . . .

Answer: For some pitfalls of scanf or scanf_s in this question, see: https://blog.csdn.net/Mr_Cat123/article/details/88563165

The source code is:
insert image description here

#include<stdio.h>

int main()
{
	int a, b;
	float x,y;
	char c1, c2;
	scanf_s("a=%db=%d", &a, &b);
	scanf_s("%f%f", &x, &y);
	scanf_s("%c%c", &c1,sizeof(c1), &c2,sizeof(c2));
	printf("a=%d,b=%d\n",a, b);
	printf("x=%f,y=%f\n", x, y);
	printf("c1=%c,c2=%c", c1, c2);
	return 0;
}

When entering a space between a=3 b=7, there will be a problem. This is because the input requirement is an integer, and the input will stop when a space (character) is encountered. So remember: scanf_s writing must be consistent with the content inside . If there is no space, do not write a space (if there is no a=%db=%d, but directly %d%d, you can leave a space, such as inputting x, y needs to be like this) The correct answer is as follows: Remember: if it is
an
insert image description here
integer Type or floating-point type, if there is no like (a=%db=%d) but direct (%d%d), a space is required in the middle. The 8th to 9th lines of the above source code are from integer to floating point, so press Enter after typing b=7, because a and b are both integers, and it will end immediately when a character is encountered, and then The x is a float. After entering y, you must not press Enter, because it is followed by a character type. Once you enter Enter, it will be the first input, that is, c1.

3.6 Please program the program. . .
#include<stdio.h>

int main()
{
	char c1='C', c2='h', c3='i', c4='n', c5='a';
	c1 = c1 + 4;
	c2 = c2 + 4;
	c3 = c3 + 4;
	c4 = c4 + 4;
	c5 = c5 + 4;
	printf("password is %c%c%c%c%c\n", c1,c2,c3,c4,c5);
	return 0;
}

insert image description here

3.7 Set the circle radius r=1.5. . . .
#include<stdio.h>
#include<math.h>

int main()
{
	float r = 1.5, h = 3, l, s, sq, vq, vz;
	float pi = 3.14159265;
	printf("Please enter radius and height:r=  h=  (Separate the two parameters with Spaces)");
	scanf_s("%f %f", &r, &h);
	l = 2 * pi*r;
	s = pi*pow(r, 2);
	sq = 4 * pi*pow(r, 2);
	vq = 3.0 / 4.0 * pi*pow(r, 3);
	vz = pi*pow(r, 2)*h;
	printf("圆周长为:       l=%6.2f\n", l);
	printf("圆面积为:       s=%6.2f\n", s);
	printf("圆球表面积为:   sq=%6.2f\n", sq);
	printf("圆球体积为:     vq=%6.2f\n", vq);
	printf("圆柱体积为:     vz=%6.2f\n", vz);
		
	return 0;
}

insert image description here

Note: The above code is 3.0/4.0 not 3/4, which is 0

unit four

4.1 What are arithmetic operations? What are relational operations? What are logical operations?

Arithmetic Operations: Use arithmetic operators to perform mathematical operations such as addition, subtraction, multiplication, and division.
Relational operation: Relational operations are comparison operations, using relational operators (<,<=,>,>=,==,!=) to compare two values.
Logical operations: Operations performed using logical operators (&&,||,!).

4.3 Write down the value of each logical expression below. Let a=3, b=4, c=5.

(1) The result of a+b>c&&b==c
is 0. Because a+b=7>c=5, the left side of && is true, which is represented by 1. b==c on the right is represented by 0. So 1&&0 results in 0
(2) a||b+c&&b-c
results in 1. The priority level on page 93, arithmetic operators are higher than relational operators, so the left side above becomes 3||9 is true, represented by 1. The right side is -1, so it is 1&&-1, neither of which is 0, so it is true, and it is represented by 1.
There are a few remaining the same logic, analyze it yourself.

4.4 3 integers, keyboard input, find the maximum value

Two methods are used here,
1. Call the function,
which is the max function in <windows.h>. If you do not write using namespace std, each max must be changed to std::max

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int a, b, c,max_value;
	scanf_s("%d%d%d", &a, &b, &c);
	max_value = max(max(a, b), c);
	printf("%d", max_value);

	return 0;
}

2 with conditional expressions

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int a, b, c,function(int,int,int);
	scanf_s("%d%d%d", &a, &b, &c);
	printf("%d", function(a,b,c));

	return 0;
}
int function(int x, int y, int z)
{
	int max_value = (x > y) ? x : y;
	return (max_value > z) ? max_value : z;

}
4.5 Input a positive number less than 1000 from the keyboard and ask to output its square root. . . .
#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int num, num1;
	printf("Please enter a positive number which is less than 1000: ");
	scanf_s("%d", &num);
	if (num >= 1000 || num <= 0)
	{
		printf("Warning, please check whether the number is positive and less than 1000\nEnter again: ");
		scanf_s("%d", &num);
	}
	num = sqrt(num);
	printf("%d", num);

	return 0;
}

4.7 There is a function: . . .

Conclusion: Neither program can be implemented. Remember: else is matched with the nearest if (the first line above P100). If the numbers of else and if are different, use curly braces. Correct as follows:

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	float x;
	int y;
	scanf_s("%f", &x);
	if (x > 0)
		y = 1;
	else
		if (x == 0) y = 0;
		else y = -1;
		printf("%d", y);
	return 0;
}

4.8 Given a one-hundred-point grade, it is required to output the grade. . . .

Here I use while, so that I can enter the next cycle after finishing one cycle

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	float score;
	char grade;
	while (TRUE)
	{
		printf("Please enter your score: ");
		scanf_s("%f", &score);
		if (score > 100 || score < 0)
		{
			printf("Please check your input score,enter again: ");
			scanf_s("%f", &score);
	     }
		switch (int (score/10))
		{
		case 10:
		case 9:grade = 'A'; break;
		case 8:grade = 'B'; break;
		case 7:grade = 'C'; break;
		case 6:grade = 'D'; break;
		case 5:
		case 4:
		case 3:
		case 2:
		case 1:
		case 0:grade = 'E'; break;

		}
		printf("Your grade is %c\n", grade);
	}
	return 0;
}

4.9 Given a positive integer with no more than 5 digits, ask:…
#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int num,place,ten_thousand,thousand,hundred,ten,individual;
	printf("Please enter a positive number (0-99999):");
	scanf_s("%d", &num);
	if (num > 9999)
		place = 5;
	else if (num > 999)
		place = 4;
	else if (num > 99)
		place = 3;
	else if (num > 9)
		place = 2;
	else place = 1;
	printf("Digit:%d", place);
	printf("Each number is: ");
	ten_thousand = num / 10000;
	thousand = (num - ten_thousand * 10000) / 1000;
	hundred = (num - ten_thousand * 10000 - thousand * 1000) / 100;
	ten = (num - ten_thousand * 10000 - thousand * 1000 - hundred * 100) / 10;
	individual = (num - ten_thousand * 10000 - thousand * 1000 - hundred * 100-ten*10);
	switch (place)
	{
	case 5:printf("%d,%d,%d,%d,%d\n", ten_thousand, thousand,hundred,ten,individual);
		printf("Inverse number:");
		printf("%d,%d,%d,%d,%d\n", individual,ten,hundred,thousand,ten_thousand);
	}

	return 0;
}

The above only gives an example of five digits, such as 10483. If you want to add 4, 3, 2, and 1 digits, just add case 4 and case 3 under the switch.

4.10 Bonuses issued by the company. . .

Here I use if to write, switch is not written, it is relatively simple.

#include<stdio.h>
#include<algorithm>
#include<functional>
using namespace std;

int main()
{
	float profit,bonus;
	printf("Please input profit:");
	scanf_s("%f", &profit);
	if (profit < 100000)
		bonus = profit*0.1;
	else if (profit < 200000)
		bonus = 100000 * 0.1 + (profit - 100000)*0.075;
	else if (profit < 400000)
		bonus = 100000 * 0.1 + 100000 * 0.075 + (profit - 200000)*0.05;
	else if (profit<600000)
		bonus= 100000 * 0.1 + 100000 * 0.075 + 200000*0.05+(profit - 400000)*0.03;
	else if (profit<1000000)
		bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000*0.03+(profit - 600000)*0.015;
	else bonus = profit*0.01;
	printf("Your bonus is %.2f", bonus);

	return 0;
}

insert image description here

4.11 Enter 4. . .

This can be achieved using the sort function, see https://blog.csdn.net/Mr_Cat123/article/details/88714096 the first function

4.12 There are 4 round towers. . .

At first glance, this question is a bit tricky, but it is actually very simple with the idea.
The key point is to judge whether the point is in the round tower. If it is, the height of the tower is 10 meters, and if it is not, it is 0. To judge whether it is in the tower, you only need to calculate whether the point p(x,y) to the center point of each tower is <=1 or not. Yes, if it is less than it is inside the tower, otherwise it is outside the tower.

#include<stdio.h>
#include<algorithm>
#include<functional>
using namespace std;

int main()
{
	float x1 = 2, y1 = 2, x2 = -2, y2 = 2, x3 = -2, y3 = -2, x4 = 2, y4 = -2,d1, d2, d3, d4,height,x,y;
	printf("Please input the coordinate of the point p(x,y):");
	scanf_s("%f%f", &x, &y);
	d1 = pow((x - x1), 2) + pow((y1 - y), 2);
	d2 = pow((x2 - x), 2) + pow((y - y2), 2);
	d3 = pow((x3 - x), 2) + pow((y - y3), 2);
	d4 = pow((x4 - x), 2) + pow((y - y4), 2);
	if (d1 <= 1 || d2 <= 1 || d3 <= 1 || d4 <= 1)
		height = 10;
	else height = 0;
	printf("The height of the point:%.2f", height);

	return 0;
}

unit five

5.2 Please add 5.7 procedures...
#include<stdio.h>
#include<algorithm>
#include<time.h>
#define SUM 10000
using namespace std;

int main()
{
	clock_t timeStart, timeEnd;
	timeStart = clock();
	int i = 0, sign = 1;
	double n = 1.0, pi = 0.0;
	for (; fabs(1.0 / n) >= 1e-6; i++)
	{
		pi = pi + sign / n;
		sign = -sign;
		n = n + 2;
	}
	timeEnd = clock();
	printf("%f\n%d\n", 4 * pi, i);
	printf("time interval=%.4f\n", (float)(timeEnd - timeStart) / CLOCKS_PER_SEC);

	return 0;
}

insert image description here
The time unit above is seconds, which is 0.01 seconds

5.4 Please enter a line of characters and count the number of English letters, spaces, numbers and other characters.

This question is more interesting and fun than some of the above questions. First of all, this question is useful in NLP (Natural Language Processing) and is more practical.
When you think of entering a line of characters, you will definitely think of using scanf_s(%s) to input. Unfortunately, scanf_s exits when it encounters a space, as shown below, so you need to
insert image description here
use gets() to input, such as:

#include<stdio.h>

using namespace std;

int main()
{
	char str[10];
	printf("Please enter a line of character:");
	gets_s(str);
	printf("%s\n", str);

	return 0;
}

insert image description here
Method 1, practical gets()

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	char str[50];
	int letters = 0, space = 0, digit = 0, other = 0;
	unsigned i;
	printf("Please enter a line of character:");
	gets_s(str);
	printf("%s\n", str);
	for (i = 0; i <= strlen(str); i++)
	{
		if (str[i] >= 'a'&&str[i]<='z' ||str[i] >= 'A'&&str[i]<='Z') letters++;
		else if (str[i] == ' ') space++;
		else if (str[i] >= '0'&&str[i]<='9') digit++;
		else other++;
	}
	printf("The length of string is %d\nletters=%d\nspace=%d\ndigit=%d\nother=%d\n",strlen(str), letters, space, digit, other-1);

	return 0;
}

Note that I set other-1 in the final output above. This is because when the input is completed, press Enter to end \n, and this key is recorded, so subtract 1. At the same time, I defined i as unsigned because of strlen (str) is a positive number when used to calculate the length, and there will be no negative numbers, so there is no need to use signed integers, and it also prevents errors: <=signed/unsigned mismatch Method 2, the idea is as follows: use getchar(
insert image description here
) , each time a character is input, when getchar()!=\n, the while will keep looping.

5.5 If n = a + aa + aaa + aaaa + aaaaa . . . . . . . . . S_n=a+aa+aaa+aaaa+aaaaa.Sn=a+aa+aaa+aaaa+a a a a a . . . , where…

Tip: For example, enter a=2, n=5.
Then the first number is a, and the second number is a × 10 + aa\times10+aa×10+a , the third number is( a × 10 + a ) × 10 + a (a\times10+a)\times10+a(a×10+a)×10+a , the fourth number is( ( a × 10 + a ) × 10 + a ) × 10 + a ((a\times10+a)\times10+a)\times10+a((a×10+a)×10+a)×10+a , you can see that these numbers are related

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int a, n,i=1,sum,f;
	printf("Please enter a and n:");
	scanf_s("%d%d", &a, &n);
	sum = f = a;
	while (i < n)
	{
		f = f*10 + a;
		sum = sum + f;
		i++;
	}
	printf("%d\n", sum);
	return 0;
}
5.6 求Σ 1 20 n ! = ( 1 ! + 2 ! + 3 ! + 4 ! + . . . ) \Sigma_{1}^{20}n!=(1!+2!+3!+4!+...)S120n!=(1!+2!+3!+4!+...)

method 1

Tip: For this question, you can first define a function factorial() to calculate the product, such as 4! =4*3*2*1. Then sum through the loop. as follows

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int j,n=20;
	long long factor,sum=0, factorial(int);
	//printf("%lld\n", ans);
	for (j = 1; j <= n; j++)
	{
		factor = factorial(j);
		sum = sum + factor;
	}
	printf("%lld\n", sum);

	return 0;
}
long long factorial(int n)
{
	int i;
	long long fact = 1;
	for (i = 1; i <= n; i++)
		fact = fact*i;
	return fact;
}

Note that due to the large amount of calculation, because 20! It is very large, so the long long type is used, otherwise there will be problems such as overflow and negative numbers.
insert image description here
In addition, the (long) integer type cannot be output exponentially, that is, it cannot be (%e). Moreover, it can be seen from the textbook that the double type can store more than long long int, so it is recommended to use the double type, that is, the code is as follows:

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int j,n=20;
	double factor,sum=0, factorial(int);
	//printf("%lld\n", ans);
	for (j = 1; j <= n; j++)
	{
		factor = factorial(j);
		sum = sum + factor;
	}
	printf("%e\n", sum);


	return 0;
}
double factorial(int n)
{
	int i;
	double fact = 1;
	for (i = 1; i <= n; i++)
		fact = fact*i;
	return fact;
}

insert image description here
Method 2

Method 1 uses the method of constructing functions, which is more intuitive, and it can also call functions when used in other places, which is relatively easy to use. But for this question itself, there is no need to call so many functions. Observe the structure of this question, which is very similar to the above question. The structure of this question is to multiply first and then sum. Even multiplication and summation can use alternative methods, that is, in the loop body, the forms of t=t*n and s=s+n.

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int n = 20, i=1;
	double t = 1, s = 0;
	while (i <= n)
	{
		t = t*i;
		s = s + t;
		i++;
	}
	printf("%e\n", s);

	return 0;
}

get the same result
insert image description here

5.7 W k = 1 100 k + . . . . . . . . . \Sigma_{k=1}^{100}k+.Sk=1100k+...

C/C++ language

#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;

int main()
{
	double sum1=0,sum2=0,sum3=0;
	int k;
	for (k = 1; k <= 100; k++)
	{
		sum1 = sum1 + k;
	}
	for (k = 1; k <= 50; k++)
	{
		sum2 = sum2 + pow(k, 2);
	}
	for (k = 1; k <= 10; k++)
	{
		sum3 = sum3 + 1.0 / k;
	}
	printf("%.3lf", sum1 + sum2 + sum3);

	return 0;
}

insert image description here
For this kind of multiplication and addition problem, python is indeed much easier to write. The following code is written in python:

import numpy as np

ans = np.sum([k for k in range(1,101)])+np.sum([k**2 for k in range(1,51)])+np.sum([1/k for k in range(1,11)])
print(ans)

insert image description here
In general, everyone says that python is slower, so I calculate the time taken by the following two.
Because the calculation is too fast, I added five 0s to the k^2 item. The C code is as follows

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>

using namespace std;

int main()
{
	clock_t timestart, timeend;
	timestart = clock();
	double sum1=0,sum2=0,sum3=0;
	int k;
	for (k = 1; k <= 100; k++)
	{
		sum1 = sum1 + k;
	}
	for (k = 1; k <= 5000000; k++)
	{
		sum2 = sum2 + pow(k, 2);
	}
	for (k = 1; k <= 10; k++)
	{
		sum3 = sum3 + 1.0 / k;
	}
	timeend = clock();
	printf("%.3lf\n", sum1 + sum2 + sum3);
	printf("It took me %.8lf seconds\n", ((float)(timeend - timestart)) / CLOCKS_PER_SEC);

	return 0
}

insert image description here

import numpy as np
import time

start = time.time()
ans = np.sum([k for k in range(1,101)])+np.sum([k**2 for k in range(1,500001)])+np.sum([1/k for k in range(1,11)])
print(ans)
end = time.time()
print("Running time is:",end-start)

insert image description here
Apparently python is more than 10 times slower than C.

Only do 13 questions below, and write the rest when you have time

5.13 Find x = ( a ) x=\sqrt(a) by iterative methodx=( a)
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>

using namespace std;

int main()
{
	float a,x0,x1;
	printf("Please enter a positive number:");
	scanf_s("%f", &a);
	x0 = a/2;
	do
	{
		x1 = (x0 + a / x0) / 2.0;
	} while (fabs(x0 - x1) > 1e-5);
	printf("The sqrt of %.2f is %.2f\n", a, x1);

	return 0;
}

unit six

6.1 Use the sieve method to find the prime numbers within 100
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	int j,i,a[101],n;
	for (i = 0; i <= 100; i++)
		a[i] = i;
	for(i=2;i<sqrt(100);i++)
		for (j = i + 1; j <= 100; j++)
		{
			if (a[i] != 0 && a[j] != 0)
			{
				if (a[j] % a[i] == 0) a[j] = 0;
			}
		
		}
	for (i = 2,n=0; i <= 100; i++)
	{
		if (a[i] != 0)
		{
			printf("%5d", a[i]);
			n++;
		}
		if(n%10==0)
		{
			printf("\n");
		}
	}
	printf("\n");
	return 0;
}

insert image description here

6.2 Sorting 10 integers by selection

It is too troublesome to enter 10 numbers here, I only enter 5

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	int j,i,a[10],t;
	printf("Please input 10 integer number:\n");
	for (i = 0; i < 5; i++)
		scanf_s("%d", &a[i]);
	for(i=0;i<10;i++)
		for (j = i + 1; j < 5; j++)
		{
			if (a[j] < a[i])
			{
				t = a[j]; a[j] = a[i]; a[i] = t;
			}
			
		}
	for (i = 0; i < 5; i++)
		printf("%5d", a[i]);
	printf("\n");
	return 0;
}

insert image description here

6.3 Find the sum of the diagonals of a 3*3 integer matrix
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	int a[3][3];
	int i, j,sum=0;
	printf("Enter data:\n");
	for (i = 0; i < 3; i++)
		for (j = 0; j < 3; j++)
			scanf_s("%d", &a[i][j]);
	for (i = 0; i < 3; i++)
	{
		sum = sum + a[i][i];
	}
	printf("%d", sum);
	printf("\n");
	return 0;
}

insert image description here

6.4 There is an array that has been sorted. It is required to enter a number and insert it into the array according to the original sorting rule.

Idea: (If the input is all integers, the sorting is also an integer, and assume that the arranged array is a[11], that is, there are 10 numbers in total, from a[0]~a[9], a[10] is used To put the incoming number. Note that there is no a[11])
1, first compare the input number nu with the number a[9] in the sorting, because a[9] is the largest, if a[9]<nu, then the assign nu to a[10]
2, if a[9]>nu, start traversing the array, find a[i]>nu, then temporarily assign a[i] to the variable temp, and assign nu to a[i ];
3, Move the numbers greater than i one bit backward (this can be done with a for loop, let’s move from the last one first, using j–)
The code is as follows:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	//int a[11] = { 1,2,3,4,5,6,7,8,9,10 };
	int a[11] = { 2,4,8,10,32, 45,60,71,74,80 };
	int i, j,temp,nu;
	printf("Enter a number:\n");
	scanf_s("%d", &nu);
	for(i=0;i<10;i++)
		if (a[i] > nu)
		{
			temp = a[i];
			a[i] = nu;

			for (j = 9; j > i; j--)
			{
				a[j + 1] = a[j];
			}
			a[i + 1] = temp;
			break;
		}
		else a[10] = nu;
	for (i = 0; i < 11; i++)
		printf("%6d", a[i]);
	printf("\n");
	return 0;
}

insert image description here

6.5 Sort the values ​​of an array counterclockwise...

1. Call the sort function: see https://blog.csdn.net/Mr_Cat123/article/details/88714096 The first function

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<functional>

using namespace std;

int main()
{
	int a[] = {8,6,5,4,1};
	int i;
	sort(a, a + 5, less<int>());
	for (i = 0; i < 5; i++)
		printf("%5d", a[i]);
	printf("\n");
	return 0;
}

2 handwritten

#define _crt_secure_no_warnings
#include<stdio.h>
#include<math.h>

using namespace std;

int main()
{
	int a[] = {8,6,5,4,1};
	int i,temp;
	int len = sizeof(a) / sizeof(a[0]); //get the length of a
	//printf("The length of array a is %d\n", len);
	for (i = 0; i < len/ 2;i++)
	{
		temp = a[i];
		a[i] = a[len-1 - i];
		a[len-1 - i] = temp;
	}
	for (i = 0; i < 5; i++)
		printf("%5d", a[i]);
	printf("\n");
	return 0;
}

insert image description here

Guess you like

Origin blog.csdn.net/Mr_Cat123/article/details/84800905