Hello everyone
I have a strange problem with floating points
This is keep track of x and y coords and change them randomly when reqested.
This just loops a load of times telling the point to move
This code will produce unexpected results like 0.1 - 0.1 = 1.49012e008. It only does it some times. I can recreate the problem in a simple example by not putting an 'f' after I declare some var (e.g. float myFloat = 0.1. However I cant see this problem in my code. Maybe I've been looking at it to long but I am sure I initiate all my floats and I am sure I put 'f' to indicate that its a float.
Does anyone have any ideas?
Thank you for your time
Andrew
I have a strange problem with floating points
This is keep track of x and y coords and change them randomly when reqested.
Code:
#include <RandGen.hpp>
using namespace std;
#ifndef _POINT_HPP_ //Check if this file has been included or not
#define _POINT_HPP_ //It has not so include and define
class Point
{
public:
~Point();
Point();
void init(float theX, float theY);
void setX(float theX);
void setY(float theY);
float getX();
float getY();
void move();
float startX;
float startY;
private:
float x;
float y;
RandGen *prg;
};
Point::Point()
{
prg = new RandGen(1,4);
x = 0.0f;
y = 0.0f;
startX = 0.0f;
startY = 0.0f;
}
Point::~Point()
{
if(prg)
delete prg;
}
void Point::init(float theX, float theY)
{
startX = theX;
startY = theY;
x = startX;
y = startY;
}
void Point::setX(float theX)
{
x = theX;
}
void Point::setY(float theY)
{
y = theY;
}
float Point::getX()
{
return x;
}
float Point::getY()
{
return y;
}
void Point::move()
{
//Select a random direction and set x and y accordingly
int dir = prg->nextRandInRange();
if(dir == 1) //north
y = y + 0.1f;
else if(dir == 2) //east
x = x + 0.1f;
else if(dir == 3) //south
y = y - 0.1f;
else if(dir ==4) //west
x = x - 0.1f;
else
cout << endl << "Epic fail";
}
#endif
This just loops a load of times telling the point to move
Code:
#include<iostream>
#include<Point.hpp>
using namespace std;
int main()
{
Point *p = new Point();
p->init(0.0f,0.0f);
for(int i = 0; i < 10000; i++)
{
p->move();
cout << endl << p->getX();
cout << endl << p->getY();
}
cout << endl << endl << "END OF PROG" << endl;
return 0;
}
This code will produce unexpected results like 0.1 - 0.1 = 1.49012e008. It only does it some times. I can recreate the problem in a simple example by not putting an 'f' after I declare some var (e.g. float myFloat = 0.1. However I cant see this problem in my code. Maybe I've been looking at it to long but I am sure I initiate all my floats and I am sure I put 'f' to indicate that its a float.
Does anyone have any ideas?
Thank you for your time
Andrew