简体   繁体   English

我如何获得点的中心?

[英]How I get center of points?

Problem: Create a vector consisting of point objects in a two-dimensional plane, calculate the average of the x and y coordinates of the point objects, and write a program that outputs the center of the points.问题:在一个二维平面上创建一个由点对象组成的向量,计算点对象的x和y坐标的平均值,并编写一个输出点中心的程序。

#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;

class Point 
{
    public:

        Point(std::string pname = NULL, int px = 0, int py = 0)

        {
            setName(pname); setX(px); setY(py);
        }

        std::string getName() { return name; }

        int getX() { return x; }

        int getY() { return y; }

        void setName(std::string pname) { name = pname; }

        void setX(int px) { x = px; }

        void setY(int py) { y = py; }

    private:

        std::string name;

        int x;

        int y;

};

int main()
{
    int a;
    int counter = 0;
    cout << "number of points" << endl;
    cin >> a;
    vector<Point> v1(a);
    while (counter < a)
    {
        Point p1;

        string tmp;
        int tmp_x;
        int tmp_y;

        cout << "name of point" << endl;
        cin >> tmp;
        p1.setName(tmp);
        
        cout << "position of point" << endl;
        cin >> tmp_x >> tmp_y;
        p1.setX(tmp_x);
        p1.setY(tmp_y);

        v1.push_back(p1);
        cout << p1.getName() <<p1.getX() << p1.getY() << endl; 
    }
    return 0;
}

this is an example of what I want (inline is keyboard input)这是我想要的一个例子(内联是键盘输入)

Number of points: 2点数: 2

Name of point: p1 position of a point: 10 20 p1 (10, 20)点名称: p1 position 点的: 10 20 p1 (10, 20)

Name of point: p2 position of a point: 40 50 p2 (40, 50)点名: p2 position 点名: 40 50 p2 (40, 50)

centor of points:(25.0, 35.0)点的中心:(25.0, 35.0)

How should I approach averaging?我应该如何进行平均?

  1. You don't need all of those #include s.您不需要所有这些#include

  2. Pay attention to NULL in class constructor.注意NULL构造函数中的 NULL。

  3. Loop continuation condition: a-- .循环继续条件: a-- Variable counter is redundant.变量counter是多余的。

  4. Vector is dynamic data structure. Vector是动态数据结构。 You don't need to declare its size explicitly, in this exercise.在本练习中,您无需显式声明其大小。 Member-function push_back will do dirty work for you.成员函数push_back将为您完成肮脏的工作。

  5. One more extra variable p1 .还有一个额外的变量p1 Try:尝试:

     v1.push_back( { tmp, tmp_x, tmp_y } );
  6. Finally...最后...

     double // if precision is necessary total_x{}, total_y{}; for ( auto& point: v1 ) { total_x += point.getX(); total_y += point.getY(); } std::cout << "Average X: " << total_x / v1.size() << "\nAverage Y: " << total_y / v1.size(); return EXIT_SUCCESS;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM