Vector-2D(for homework)
标签(空格分隔): 程序设计实验 c++
本人学院
Description:
Please create a class Vector.
The declaration of Vector is in ‘Vector.h’
before programing, you should revise the operations between vectors.
note:
add() vecter1 + vecter2
sub() vecter1 - vecter2
rev() means reverse of the vector like (1, 2) -> (-1, -2);
dot_product() 点乘;
cross_product() 叉乘(返回 int,使用abs函数取绝对值);
print() display the vecter in the form like “(1, 2)\n”;
main.cpp
#include <iostream>
#include "Vector.h"
using namespace std;
int main() {
// test#
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Vector vec1(x1, y1);
Vector vec2(x2, y2);
Vector vec3 = vec1.add(vec2);
vec3.print();
Vector vec4 = vec1.sub(vec2);
vec4.print();
Vector vec5 = vec1.inverse();
vec5.print();
int dot_result = vec1.dot_product(vec2);
cout << "dot product equal:" << dot_result << ".\n";
int cross_result = vec1.cross_product(vec2);
cout << "cross product equal:" << cross_result << ".\n";
return 0;
}
Vector.h
#ifndef VECTOR_H
#define VECTOR_H
using namespace std;
class Vector {
public:
// constructer
Vector();
Vector(int, int);
// copy constructer
Vector(const Vector &otherVec);
// destructer
~Vector() {}
// vecter1 + vecter2
Vector add(Vector);
// vecter1 - vecter2
Vector sub(Vector);
// -vecter1
Vector inverse();
// vecter1 * vecter2
int dot_product(Vector);
// vecter1 x vecter2
int cross_product(Vector);
void print();
private:
int x, y;
};
#endif
读题
my answer
#include<iostream>
#include<cmath>
#include"Vector.h"
using namespace std;
Vector::Vector() {
x = 0;
y = 0;
}
Vector::Vector(int newX, int newY) {
x = newX;
y = newY;
}
// copy constructer
Vector::Vector(const Vector &otherVec) {
x = otherVec.x;
y = otherVec.y;
}
// vecter1 + vecter2
Vector Vector::add(Vector v) {
Vector other;
other.x = x + v.x;
other.y = y + v.y;
return other;
}
// vecter1 - vecter2
Vector Vector::sub(Vector v) {
Vector other;
other.x = x - v.x;
other.y = y - v.y;
return other;
}
// -vecter1
Vector Vector::inverse() {
Vector v;
v.x = 0 - x;
v.y = 0 - y;
return v;
}
// vecter1 * vecter2
int Vector::dot_product(Vector v) {
return x * v.x + y * v.y;
}
// vecter1 x vecter2
int Vector::cross_product(Vector v) {
double pro = static_cast<double>(x * v.y - y * v.x);
int ans = static_cast<int>(abs(pro));
return ans;
}
void Vector::print() {
cout << "(" << x << ", " << y << ")" <<endl;
}
the standard answer
#include "Vector.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
Vector::Vector() {
x = y = 0;
}
Vector::Vector(int a, int b) {
x = a;
y = b;
}
Vector::Vector(const Vector &otherVec) {
x = otherVec.x;
y = otherVec.y;
}
Vector Vector::add(Vector v) {
return Vector(x+v.x, y+v.y);
}
Vector Vector::sub(Vector v) {
return Vector(x-v.x, y-v.y);
}
Vector Vector::inverse() {
return Vector(-x, -y);
}
int Vector::dot_product(Vector v) {
return x*v.x+y*v.y;
}
int Vector::cross_product(Vector v) {
return abs(x*v.y-y*v.x);
}
void Vector::print() {
cout << "(" << x << ", " << y << ")\n";
}
反思
直接用构造函数返回成员