0

I am trying to store coordinate points in a double variable. It is very simple. I have x and y coordinates. My double variable stores them like that x.y . When I tried to convert this value into separate coordinates, I had some troubles.

I have tried these codes but still get same error.

 //First try
 double temp=memory.pop();
 int x=(int)temp;
 int y=(int)((temp-(int)temp)*100);
 //Second try
 double temp=memory.pop();
 int x=(int)temp;
 int y=100.0f*temp-(((int)temp)*100.0f);

In temp variable, I have 5.14 double number. After calculations, x should be 5 and y should be 14. However, x become 5, y become 13.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
numudoka
  • 25
  • 7
  • 3
    Sorry but that is a terrible idea. Floating point numbers don't have infinite precision at all. Use two variables. – Mat Mar 26 '19 at 09:58
  • 1
    You "could" store two `int32_t` as `uint32_t` in a single `uint64_t` and access them using bit shifting and bit masking, but why don't you simply use a `class` with two `int`? – Bob__ Mar 26 '19 at 10:21

1 Answers1

2

The issue is related to integer casting. Specfically (int)temp will floor to the first smaller integer. For insance, the value 5,14 can be (and probably is) not exaclty that but a bit smaller/larger for a matter of precision (since, as said in comments, the floating point numbers don't have infinite precision). So without loss of generality let's say that is 5,13999999999999, you can see that when you perform your operation you will obtain 13 instead of 14 for the second part of the coordinate.

NiVeR
  • 9,644
  • 4
  • 30
  • 35