When multiplying vectors, why do I get -0.000000 results?

I've got the following operator overload for my Vector Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// vec3.cpp
Vec3 Vec3::operator+(const Vec3 &v) const {
    return Vec3(x + v.x, y + v.y, z + v.z);
}

// Main
Vec3 a(0,0,0);
Vec3 b(0,0,0);
Vec3 result(0,0,0);

result = a + b;

result.Print(); // and I get vec: 0.000000 0.000000 -3.5005043
// sometimes I get -0.000000, or any other random positive or neg number.  


My result's z property is never getting full zero's. Always a negative zero, sometimes a random positive or negative number, but never zeros like x and y. And I'm only adding two vector's of zeros.

I also checked if my a and b vectors are instantiating anything other than zeros, and no, everything is fine.

By the way, result.Print() is a function the Vector Class has where I simply use:

printf("%f,%f,%f\n",x,y,z);

Would anybody know why I get random numbers when adding to floating point zero's?
Last edited on
closed account (48bpfSEw)
can you post us your constructor and copy operator of Vec3, too?
Sure, no problem:

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
28
29
30
31
32

// .h
class Vec3 {
public:
	Vec3() { x = y = z = 0; }
	Vec3(float x, float y, float z) {
		x = x; y = y; z = z;
	}	
	Vec3(float XYZ[3]) {
		x = XYZ[0];
		y = XYZ[1];
		z = XYZ[2];
	}
	union {
		struct { float x,y,z;};
		float v[3];
	};

	void Print();
	Vec3 operator+(const Vec3 &v) const;

};

// .cpp
void Vec3::Print() {
	printf(" %f, %f, %f \n",x,y,z);
}

Vec3 Vec3::operator+(const Vec3 &v) const {
	return Vec3(x + v.x, y + v.y, z + v.z);
}


If you need more, let me know.
Last edited on
closed account (48bpfSEw)
look closer:

1
2
3
	Vec3(float x, float y, float z) {
		x = x; y = y; z = z;
	}



did you mean:

1
2
3
	Vec3(float x, float y, float z) {
		this->x = x; this->y = y; this->z = z;
	}


Necip thanks a lot! I had no idea you HAD to use this. I thought the compiler assumed I meant this class by using x,y,z in that scope. Now I know :)
hashbrown wrote:
I thought the compiler assumed I meant this class by using x,y,z in that scope.

If that was the case it would be assigning the class variables to themselves so it would still not work.
 
this->x = this->x; ...

If you instead use the constructor initialization list you don't have to use this.
 
Vec3(float x, float y, float z) : x(x), y(y), z(z) {}
Last edited on
Thanks for clarifying that Peter87. I wasn't understanding that.
closed account (48bpfSEw)
i wrote:

this->x = x;


the left x is the x of the class,
the right x is the param of the constructor
Topic archived. No new replies allowed.