Coordinate

Purpose:

① Understand the concepts of classes and objects, and master the methods of declaring classes and defining objects.

② Master the implementation methods of constructors and destructors.

③ Have a preliminary grasp of C++programming using classes and objects

Basic tasks:

Create a class to complete the following functions:

① . Continuously input a set of 2-digit coordinate values;

② The number of two-dimensional coordinate values can be user-defined (2 by default, 100 at most);

③ Display the coordinate value entered by the user;

④ Display the mean value of the coordinate value entered by the user;

#include <iostream>
using namespace std;
class Coordinate {
public:
	Coordinate()
	{
		times = 2; //设置默认输入坐标数目
		cout<< "构造函数1被调用。"<<endl;
	}
	Coordinate(int times1)
	{
		times = times1;
		cout << "构造函数2被调用,坐标数为:" << times << endl;
	}
	~Coordinate()
	{
		cout << "析构函数被调用" << endl;
	}
	void InputCoord()
	{
		int i;
		for (i = 0; i < times; i++)
		{
			cout << "请输入第" << i + 1 << "个坐标的横坐标:" << endl;
			cin >> Coord[i][0];
		}

		for (i = 0; i < times; i++)
		{
			cout << "请输入第" << i + 1 << "个坐标的纵坐标:" << endl;
			cin >> Coord[i][1];
		}
	}
	void ShowCoord()
	{
		int i;
		for (i = 0; i < times; i++)
		{
			cout << "第" << i + 1 << "个坐标为" << Coord[i][0] << ',' << Coord[i][1] << endl;
		}
	}
	void ShowAvgCoord()
	{
		int i;
		float avgx, avgy, sumx = 0, sumy = 0;
		for (i = 0; i < times; i++)
		{
			sumx = sumx + Coord[i][0];
			sumy = sumy + Coord[i][1];
		}
		avgx = sumx / times;
		avgy = sumy / times;
		cout << "横坐标平均值为:" << avgx << endl;
		cout << "纵坐标平均值为:" << avgy << endl;
	}
private:
	float Coord[100][100];
	int times;
};
int main()
{
	int num;
	cout << "是否需要改变输入坐标数目(默认值为2,最多可以为100个)?需要改变请按1,无需改变请按0:";
	cin >> num;
	if (num == 1)
	{
		int coordinate_numebr;
		cout << "请输入要更改的坐标数目:";
		cin >> coordinate_numebr;
		Coordinate x(coordinate_numebr);
		x.InputCoord();
		x.ShowCoord();
		x.ShowAvgCoord();
		return 0;
	}
	if (num == 0)
	{
		Coordinate x;
		x.InputCoord();
		x.ShowCoord();
		x.ShowAvgCoord();
		return 0;
	}
}

Through the code given in the course, build a Coordinate class, input the coordinate values of x and y through the keyboard, then output (x, y), and calculate the average value of the coordinates. Then call the annotated part of the code. It is found from the running results that the input coordinate function is called again after the original function is executed. You can input 5 groups of coordinates, output (x, y) and average coordinates.

After starting to run in the program, first call the constructor content, and then run the input coordinate program. When the function is completed, call the destructor

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值