c++ – Members return inf. C ++

Question:

The class that contains the object of the vector2d structure

class Foo {

public:
    Foo() {
        acceleration_force = vector2d();
        //acceleration_force(); не видит конструктора вообще
        cout << "acc x: " << acceleration_force.x << " y: " << acceleration_force.y << endl;
    }
private:
    vector2d acceleration_force;
};

My structure is vector2d

#ifndef VECTORS_H
#define VECTORS_H

struct vector2d {

    vector2d(float y, float x) : y(y), x(x) {}
    vector2d() : y(-1), x(0) {}

    float y, x;
};

#endif /* VECTORS_H */

The output is acc x: inf y: -inf

While the same code works successfully on ideone

I print the text using ncurses using the printw function.


It looks like I have a problem with pointers and links, since the debugger shows everything correctly.

AddAcceleration function:

void AddAcceleration(vector2d direction, float value) {
    acceleration_force = (direction.normal()*value) * mass;
}

vector2d::normal() function

vector2d normal() {
    vector2d result(*this);
    result.x = result.length() / result.x;
    result.y = result.length() / result.y;
    return result;
}

GetForce function:

vector2d GetForce() {
    return acceleration_force;
}

vector2d::lenght :

float length() {
    return sqrt(y*y+x*x);
}

Foo class variables:

private:
    float mass;
    vector2d acceleration_force;
    float speed;
    vector2d friction;
    vector2d force;
    vector2d direction;

GetMass() , GetSpeed() simple getters.

A section of code that displays the values ​​of a vector:

foo = Foo();
foo.AddAcceleration(vector2d(-1,0), 2);
printw("%f, %f", mov.GetForce().x, mov.GetForce().y);

Also, I also ask you to look at the classes where I overloaded the operators * and + the vector2d structure. They, too, as I understand it, do not work:

vector2d operator+(const vector2d& right) const {
    vector2d result(*this); // Make a copy of myself.
    result.x += right.x;
    result.y += right.y;
    return result;
}

vector2d operator*(const float right) const {
    vector2d result(*this);
    result.x *= right;
    result.y *= right;
    return result;
}

Answer:

I figured out what the problem is inf , -inf .
When х = 0, y = -1 , the length is sqrt( -1 * -1 + 0 * 0) == 1 , the variable x becomes x = 1 / x = 1 / 0 = inf , then the length is already considered as sqrt ( -1 * -1 * inf * inf) . Plus it was necessary, on the contrary, to divide the coordinate by the length of the vector. And multiplication by mass gives nan , because mass not initialized

Scroll to Top