Exercise day1 (basic exercise)

Keywords: C++

Reprint: CPlusPlusThings/practical_exercises/10_day_practice/day1 at master · Light-City/CPlusPlusThings · GitHub

The code is another online swing, which is different from the original website

1. Leap year

#include<iostream>
using namespace  std;
int main(int argc, char const *argv[])
{
	int year;
	bool isLeapyear;
	cout << "please enter year" << endl;
	cin >> year;
	isLeapyear = (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
	if (isLeapyear)
		cout << "yes" << endl;
	else
		cout << "no" << endl;
	system("pause");
	return 0;
}

2. Consortium learning

#include<iostream>
using namespace  std;

union muun {
	struct { int x; int y; int z; }u;
	int k;
	int i;
	int j;
}a;
int main()
{
	a.u.x = 1;
	a.u.y = 2;
	a.u.z = 3;
	a.k = 4;//The first element in structure u will be overwritten, and I don't understand why the first element is overwritten instead of the second element
	printf("%d %d %d %d\n", a.u.x, a.u.y, a.u.z, a.k);
	return 0;
}

Structure: combine different types of data into a whole. The memory length occupied is the sum of the memory length occupied by each member. So an int k can only cover an int x. It should be

3.x to the n th power

#include<iostream>
using namespace  std;
double power(double x, int n);
int main(int argc, char const argv[])//This is a relatively standard way to write the main function
{
	double x=0.0;//Local variables are initialized randomly
	int n=0;
	cout << "please enter x and n" << endl;
	cin >> x >> n;
	cout << x << "of" << n << "Power equals" << power(x, n) << endl;
	return 0;
}

double power(double x, int n)
{
	double val = 1.0;
	while (n--)
		val *= x;
	return val;
}

4. Roll dice (by class)

#include<iostream>
#include<ctime>
using namespace  std;
class dice {
public:
	int getNumber();
private:
	int number;
};

int main()
{
	dice d;
	cout << d.getNumber() << endl;
	return 0;
}


int dice::getNumber()
{
	srand((unsigned)time(NULL));//Generate random number seed
	number = rand() % 6 + 1;
	return number;

}

5. Enumeration type

#include<iostream>
using namespace  std;
//If the parameter type is defined as enumeration class in the parameter list of the method, the parameter value can only be selected from the enumeration items of the enumeration class when passing parameters, and there will be no scribble.
enum weekday
{
	monday,tuesday,wednesday,thursday,friday,saturday,sunday
};

int main(int argc, char const *argv[])
{
	enum weekday wek = monday;
	for (weekday i = wek; i != saturday; i++)
	{
		cout << i << endl;
		cout << wek + monday << endl;
	}
	return 0;
}

6. Tower of Hanoi

Reprint: c + + implementation of Hanoi Tower problem_ GinSmile blog - CSDN blog_ Hanoi Tower c++

On one column, 64 gold discs are stacked in size order from bottom to top. Find out how many times it needs to be moved to rearrange the discs on another column in size order from below. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three columns at a time.

answer:

We can take n=3 as an example:

It is easy to know that f (1) = 1, f (2) = 3, f (3) = 7;

When n=2 (1, 2 and 3 represent small, medium and large plates respectively):

When n=3:

The first three steps of n=3 are to move the small two to another column when n=2 is repeated.

Then move 3 to another column. Continue to repeat n=2 and move the small two to another column (referring to the one with 3).

Extended to N, that is, f (n) = 2*f (n-1) + 1     

        To solve this problem, suppose you already know how to move N-1 rings. Now, in order to move the ring on the starting disk A to the target disk C, suppose the disks are ABC:

1. Move N-1 rings from disk A to disk B without any rings;
2. Move the last ring from disk A to Disk C;
3. Move N-1 rings from disk B to Disk C (solve the problem by imitating the operation methods of 1 and 2).
 

#include<iostream>
using namespace  std;
/*To solve this problem, suppose you already know how to move N-1 rings. Now, in order to move the ring on the starting disk A to the target disk C, suppose the disks are ABC:

1,Move N-1 rings from disk A to disk B without any rings;
2,Move the last ring from disk A to Disk C;
3,Move N-1 rings from disk B to Disk C (solve the problem by imitating the operation methods of 1 and 2).
*/
void hannoi(int n, char A, char B, char C)
{
	if (n == 1)
		cout << "Disc" << n << "from" << A << "put to" << C << endl;
	else {
		hannoi(n - 1, A, C, B);//1. Move N-1 rings from disk A to disk B without any rings;
		cout << "Disc" << n << "from" << A << "Move to" << C << endl;
		hannoi(n - 1, B, A, C);//3. Move N-1 rings from disk B to disk C
	}
}

int main()
{
	int n = 0;
	cout << "Please enter the number of discs" << endl;
	cin >> n;
	hannoi(n, 'A', 'B', 'C');
	return 0;
}

7. Structure

#include<iostream>
using namespace  std;
struct student {
	int num;
	char name[10];
	char gender;
};

int main(int argc, char const *argv[])
{
	student s = { 10,"assd",'m' };
	cout << s.num << endl;
	cout << sizeof(s.num) << endl;//0
	cout << sizeof(s.name) << endl;//
	cout << sizeof(s.gender) << endl;
	cout << sizeof(s)<<endl;
	/*  Offset refers to the difference between the address of the member in the structure variable and the address of the structure variable. The structure size is equal to the offset of the last member plus the size of the last member.
	Obviously, the address of the first member in the structure variable is the first address of the structure variable. For example, in the above structure, the offset of the first member a is 0.
	The offset of the second member b is the offset of the first member plus the size of the first member (0 + 4), and its value is 4; The offset of the third member c is the offset of the second member, which should be plus the size of the second member (4 + 1).
*/
	return 0;
}

8. Comprehensive function exercises
A circular swimming pool is shown in the figure. Now a circular aisle needs to be built around it and fenced around it. The price of fence is 35 yuan / m, and the cost of aisle is 20 yuan / m2.
The aisle width is 3M, and the radius of the swimming pool is entered by the keyboard. It is required to program, calculate and output the cost of aisle and fence.
Graphic description: large circle nested small circle:
The small circle is in the middle of the big circle, the small circle is the swimming pool, and the gap between the big circle and the small circle is the aisle.

#include<iostream>
#include<math.h>
using namespace  std;
const float PI = 3.14;
const float FencePrice = 35;
const float ConcretePrice = 20;
class Circle {
public:
	Circle(float r);
	float FencePerimeter()const;//This function is read-only and it is not allowed to modify the value of the data member in it.
	float Area()const;

private:
	float radius;
};
Circle::Circle(float r)
{
	radius = r;
}
float Circle::FencePerimeter()const {
	return 2 * PI*radius + 2 * PI*(radius + 3);
}
float Circle::Area()const
{
	return PI * (pow((radius + 3),2 )-pow(radius,2));
}
int main()
{
	
	cout << "Please enter the swimming pool radius" << endl;
	int r = 0;
	cin >> r;
	Circle c(r);
	
	cout << "Fence cost:" << c.FencePerimeter()*FencePrice << endl;
	cout << "Aisle cost:" << c.Area()*FencePrice << endl;
	return 0;
}

9. Class forward declaration

/*
Although using forward reference declaration can solve some problems, it is not omnipotent. It should be noted that,
Although the forward reference declaration is used, the object of the class cannot be declared until a complete class declaration is provided,
You cannot use objects of this class in inline member functions. See the following program section:
*/

//First kind
#include<iostream>
class Fred;	//Forward reference declaration
class Barney {
   Fred x;	//Error: Declaration of class Fred is incomplete
};
class Fred {
   Barney y;
};


//Second
class Fred;	//Forward reference declaration
 
class Barney {
 public:
   void method()
   {
     x->yabbaDabbaDo();	//Error: object of Fred class was used before definition
   }
 private:
   Fred* x;   //Correct. After the forward reference declaration, you can declare the object pointer of Fred class
 };
 
class Fred {
 public:
   void yabbaDabbaDo();
 private:
   Barney* y;
}; 

/*
Summary: when using forward reference declarations, only the declared symbols can be used, and no details of the class can be involved.
*/

10. Static member function

/*
Knowledge points:
Static member function
 Out of class code can use class names and scope operators to call static member functions.
Static member functions can only reference static data members or static member functions that belong to this class.
*/
#include<iostream>
using namespace std;
class Application
{ 
public:
    static void f(); 
    static void g();
private:
    static int global;
};
int Application::global=0;
void Application::f()
{  global=5;}
void Application::g()
{  cout<<global<<endl;}

int main()
{
    Application::f();
    Application::g();
    system("pause");
    return 0;
}
#include<iostream>
using namespace std;
class A
{
    public:
        static void f(A a);
    private:
        int x;
};
void A::f(A a)
{
   
    //Static member functions can only reference static data members or static member functions that belong to this class.
    // cout<<x; // The reference to X is wrong
    cout<<a.x;  //correct
}

int main(int argc, char const *argv[])
{
    A a;
    a.f(A());
    system("pause");
    return 0;
}

11. Static data members

/*
Learning knowledge:
Static data member
 Declare with keyword static
 All objects of this class maintain the same copy of this member
 Must be defined and initialized outside the class. Use (::) to indicate the class to which it belongs.
*/
#include <iostream>
using namespace std;
class Point	
{
public:	
	Point(int xx=0, int yy=0) {X=xx; Y=yy; countP++; } 
    Point(Point &p);	
	int GetX() {return X;}
	int GetY() {return Y;}
	void GetC() {cout<<" Object id="<<countP<<endl;}
private:	
	int X,Y;
    //Static data members must be defined and initialized externally, and cannot be initialized directly internally!
	static int countP;
};
Point::Point(Point &p)
{	X=p.X;
	Y=p.Y;
	countP++;
}
//Must be defined and initialized outside the class. Use (::) to indicate the class to which it belongs.
int Point::countP=0; 
int main()	
{	Point A(4,5);	
	cout<<"Point A,"<<A.GetX()<<","<<A.GetY();
	A.GetC();	
	Point B(A);	
	cout<<"Point B,"<<B.GetX()<<","<<B.GetY();
	B.GetC();	
    system("pause");
    return 0;
}

Posted by InO on Wed, 13 Oct 2021 12:13:21 -0700