C++折線總長度計算

這是一次c++作業,可能會有點做的不好,如果有問題希望大家可以指出,謝謝!
下面是 我寫的代碼

#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

class CCoordinate       //座標類
{
private:
	int x;
	int y;
public:
	int get_x();
	int get_y();
	void set_x(int a);
	void set_y(int b);
};

typedef vector<CCoordinate> Allcoor;     //座標容器

class CLineLength                     //計算長度
{
public:
	int differ(int a, int b);
	float Length(int xx, int yy);
	Allcoor InAllcoor(int n);
	void ToLength(Allcoor allcoor);
};

int main()
{
	int n;
	CLineLength LineLength;
	cout << "請輸入折線端點個數以及全部座標:(按照順序)" << endl;
	cin >> n;
	Allcoor inallcoor=LineLength.InAllcoor(n);
	LineLength.ToLength(inallcoor);
	return 0;
}

void CCoordinate::set_x(int a)
{
	x = a;
}
void CCoordinate::set_y(int b)
{
	y = b;
}
int CCoordinate::get_x()
{
	return x;
}
int CCoordinate::get_y()
{
	return y;
}

int CLineLength::differ(int a, int b)
{
	return (a - b);
}
float CLineLength::Length(int xx, int yy)
{
	float Length;
	Length = sqrt(float(xx * xx + yy * yy));
	return Length;
}
Allcoor CLineLength::InAllcoor(int n)
{
	Allcoor allcoor;
	for (int i = 0; i < n; i++)
	{
		int x, y;
		CCoordinate ccoor;
		cin >> x >> y;
		ccoor.set_x(x);
		ccoor.set_y(y);
		allcoor.push_back(ccoor);

	}
	return allcoor;
}
void CLineLength::ToLength(Allcoor allcoor)
{
	float tolength=0;
	for (int j = 0; j < (allcoor.size() - 1); j++)
	{
		int x = differ(allcoor[j].get_x(), allcoor[j + 1].get_x());
		int y = differ(allcoor[j].get_y(), allcoor[j + 1].get_y());
		tolength = tolength + Length(x, y);
	}
	cout << "折線的總長度爲" << tolength << endl;
}

運行結果:
運行結果
注意:座標的x,y空格隔開,均爲整型,但折線總長度爲浮點型。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章