The position of a point
Question:
Specify, design, and implement a class that can be used to keep track of the position of a point in three-dimensional space. For example, consider the point drawn at the picture below. The point shown there has three coordinates: x = 2.5, y = 0, and z = 2.0. Include member functions to set a point to a specified location, to shift a point a given amount along one of the axes, and to retrieve the coordinates of a point. Also provide member functions that will rotate the point by a specified angle around a specified axis.
To compute these rotations, you will need a bit of trigonometry. Suppose you have a point with coordinates x, y, and z. After rotating this point (counter-clockwise) by an angle , the point will have new coordinates, which we’ll call , , and . The equations for the new coordinates use the cmath library functions sin and cos, as shown here:
After a rotation around the x-axis:
After a rotation around the y-axis:
After a rotation around the z-axis:
My answer:
point.h
#pragma once
class point {
public:
point() {
x = y = z = 0;
};
point(double m, double n, double q) {
set_position(m, n, q);
};
void set_position(double m, double n, double q);
void move_x(double m);
void move_y(double m);
void move_z(double m);
void rotate_x(double a);
void rotate_y(double a);
void rotate_z(double a);
void print_point();
private:
double x, y, z;
};
point.cpp
#include "pch.h"
#include "point.h"
#include <cmath>
#include <iostream>
void point::set_position(double m, double n, double q)
{
x = m;
y = n;
z = q;
}
void point::move_x(double m)
{
std::cout << "shift along x-axis by " << m << std::endl;
x += m;
}
void point::move_y(double m)
{
std::cout << "shift along y-axis by " << m << std::endl;
y += m;
}
void point::move_z(double m)
{
std::cout << "shift along z-axis by " << m << std::endl;
z += m;
}
void point::rotate_x(double a)
{
std::cout << "rotate around the x-axis by " << a << std::endl;
double tmp_y;
tmp_y = y * cos(a) - z * sin(a);
z = y * sin(a) + z * cos(a);
y = tmp_y;
}
void point::rotate_y(double a)
{
std::cout << "rotate around the y-axis by " << a << std::endl;
double tmp_x;
tmp_x = x * cos(a) + z * sin(a);
z = -x * sin(a) + z * cos(a);
x = tmp_x;
}
void point::rotate_z(double a)
{
std::cout << "rotate around the z-axis by " << a << std::endl;
double tmp_x;
tmp_x = x * cos(a) - y * sin(a);
y = x * sin(a) + y * cos(a);
x = tmp_x;
}
void point::print_point()
{
std::cout << "(x, y, z) = (" << x << ", " << y << ", " << z << ")" << std::endl;
}
测试代码:
#include "point.h"
#include <iostream>
#define PI 3.14159265
int main()
{
point a(2.5, 0, 2.0);
a.move_x(1);
a.move_y(1.5);
a.move_z(-2.5);
a.rotate_x(PI / 2);
a.rotate_y(PI / 4);
a.rotate_z(3 * PI / 4);
a.print_point();
a.set_position(5, 5, 5);
a.print_point();
}
结果:
reference:
整理自《Data Structures and Other Objects Using C++ ( Fourth Edition )》Michael Main, Walter Savitch. p120