LearnFrenzy
Sign in Take a free test

Classes and Objects · Class Programs · Question 6

Point class: distance, midpoint and centroid in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write a Point class with distance_to, midpoint and a static centroid function for a vector of points, and print the results.

Solution
main.cpp
#include <cmath>
#include <iostream>
#include <vector>

class Point {
    double x_, y_;
public:
    Point(double x = 0, double y = 0) : x_(x), y_(y) {}
    double distance_to(const Point& o) const { return std::hypot(x_ - o.x_, y_ - o.y_); }
    Point midpoint(const Point& o) const { return {(x_ + o.x_) / 2, (y_ + o.y_) / 2}; }
    static Point centroid(const std::vector<Point>& pts) {
        double sx = 0, sy = 0;
        for (const auto& p : pts) { sx += p.x_; sy += p.y_; }
        return {sx / pts.size(), sy / pts.size()};
    }
    friend std::ostream& operator<<(std::ostream& os, const Point& p) {
        return os << '(' << p.x_ << ", " << p.y_ << ')';
    }
};

int main() {
    Point a(0, 0), b(6, 8), c(3, -2);
    std::cout << a.distance_to(b) << ' ' << a.midpoint(b) << ' ' << Point::centroid({a, b, c}) << '\n';
    return 0;
}

Output Verified by compiling and running

10 (3, 4) (3, 2)

std::hypot computes √(dx² + dy²). centroid is static because it works on a collection rather than on one point, yet as a member it may read the private coordinates.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links