SDUST 实验+ 作业

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了,因为测试样例很多,所以会超很多,不是由于循环造成的
//
//字符串类出错的原因是: 定义了太多字符串,复制来复制去,自己也就晕了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值