Adding 2 vectors

Why is the result wrong?
1.79302e-307,1.79317e-307+-8.94132e+070,2.60732e+253=7.23027e-308,7.23127e-308

Correct result should be :(1.5, 8.0)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
#include <fstream>
using namespace std;

class Vector2D {
private:
    double x, y;
public:

    Vector2D (double x, double y) {
    }
    friend Vector2D operator +(Vector2D a, Vector2D b){
        return Vector2D(a.x*b.x, a.y*b.y);
    }
    friend ostream& operator << (ostream& s , Vector2D v){
        return s << v.x << "," << v.y ;
    }
};


int main() {
    Vector2D a(2.5, 2.0);
    Vector2D b(-1, 6);

    Vector2D c = a + b;   // (1.5, 8.0)
    cout << a  << "+"  << b << "=" << c <<'\n';
}
Last edited on
You need to initialize the member variables x and y (you have the constructor, but you don't have anything in it). Also, should you be adding a.x and b.x, and a.y and b.y instead of multiplying them?
Topic archived. No new replies allowed.