Problem 质心算法
注意点: 浮点数精确位数的确定 用iompion 头文件下的 setprecision(); 不要忘记了
new 和 delete 的用法
new的功能类似于malloc, 用于从堆内存中分配指定大小的内存区域, 并返回获得的内存区域的!!!首地址!!!
#include<iostream>
#include<iomanip>
#define LOCAL
#include<cstdio>
using namespace std;
class Point
{
public:
Point(): x_(0), y_(0)
{
cout << "The Point ("<< setprecision(2)<<fixed << x_ << ", " << y_ << ") is created!" <<endl;
}
Point(double x, double y) : x_(x), y_(y)
{
cout << "The Point ("<< setprecision(2)<<fixed << x_ << ", " << y_ << ") is created!" <<endl;
}
Point(const Point & p): x_(p.x_), y_(p.y_)
{
cout << "A Point ("<< setprecision(2)<<fixed << x_ << ", " << y_ << ") is copied!" <<endl;
}
double getX()
{
return x_;
}
double getY()
{
return y_;
}
~Point()
{
cout << "A Point ("<< setprecision(2)<<fixed << x_ << ", " << y_ << ") is erased!" <<endl;
}
//private:
double x_, y_;
};
class Graph
{
public:
Graph(Point *p, int num)
{
n_ = num;
p_ = new Point[num]; // 给Graph中的p_分配内存
//p_ = p; //这样会崩
for(int i = 0; i < num; i++)
p_[i] = p[i];
cout << "A graph with " << n_ << " points is created!" << endl;
}
Point getCentroid()
{
double x, y, sumx = 0, sumy = 0;
for(int i = 0; i < n_; i++)
{
sumx += p_[i].getX();
sumy += p_[i].getY();
}
x = sumx / n_;
y = sumy / n_;
Point* p = new Point(x, y);
return *p;
}
~Graph()
{
delete []p_;
cout << "A graph with " << n_ << " points is erased!" << endl;
}
private:
int n_;
Point* p_;
};
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif // LOCAL
int cases,num;
double x, y;
Point centroid;
cin>>cases;
for (int i = 0; i < cases; i++)
{
cin>>num;
Point points[num];
for (int j = 0; j < num; j++)
{
cin>>x>>y;
points[j] = *(new Point(x, y));
}
Graph graph(points, num);
centroid = graph.getCentroid();
cout<<setprecision(2)<<fixed<<"The centroid is ("<<centroid.getX()<<", "<<centroid.getY()<<")."<<endl;
}
return 0;
}
作业总结:
//呵呵自动机出错的原因是:如果开头只剩一个元素了就把那一个元素输出就可以了
//不要在输出NULL了,因为测试样例很多,所以会超很多,不是由于循环造成的
//
//字符串类出错的原因是: 定义了太多字符串,复制来复制去,自己也就晕了。