0

I am trying to use a function in windows form application that convert a given point to another coordinate system. However, I encountered a strange problem. The input are correct but output is always 0. First, I thought it caused because of the local variables and then instead of variables I used only integers but it did not solve. I have no idea about it. Here the code and output basically:

string[] newPoint1 = convertPoints(X1, Y1);

string[] convertPoints(int oldX, int oldY)
        {
            //int newX = ((oldX - oldLeft) / (oldRight - oldLeft)) * (newRight - newLeft);
            MessageBox.Show(oldX.ToString());   // output is 296 
            int newX = (oldX / 500) * 4096;   // ?????????????????????  (296/500) * 4096  = 0 ?????????????
            MessageBox.Show(newX.ToString()); // here output is 0
            int newY = newTop + ((oldY - oldTop) / (oldBottom - oldTop)) * (newBottom - newTop);
            
            //MessageBox.Show(newY.ToString());
            string[] newPoints = {newX.ToString(), newY.ToString()};
            //MessageBox.Show(newPoints[0], newPoints[1]);
            return newPoints;
        }

3 Answers3

1

This is working as it should. Because oldX is an Integer, when you divide it, it rounds (drops anything after the decimal). I would convert it to float and back into an integer, like so

int newX  = (int)(((float)oldX / 500) * 4096);

This will preserve the whole number until you're done at the end. You'll also need to do the same for the Y values

davidsbro
  • 2,761
  • 4
  • 23
  • 33
0

You are getting 0 because oldX/500 is a fraction usually and since you are using the int datatypes there can only be whole numbers. What I would recommend doing is changing the data type then rounding yourself.

  //Old code
  int newX = (1 / 500);
  Console.WriteLine(newX);
  // writes 0 to console


  //New code
  double newXD = (1 / 500.0) * 4096;
  Console.WriteLine(newXD);
  //Writes 8.192

The 1 and the 500 are considered ints try

Console.WriteLine(1/500);

It writes 0 to the console.

Console.WriteLine(1/500.0);
Console.WriteLine((float)1/500);
Console.WriteLine((double)1/500);

All these write 8.192 to the console.

Then after you have the double or other more accurate data type consider rounding if you really want an int.

Daniel Kelsch
  • 393
  • 2
  • 10
0

An integer division cuts off the decimal places. So in your case, 296/500 you would expect 0.592. As integer has no decimal places, it cuts off them off resulting in 0.

Change the oldX to double and divide by 500.0

Marcii
  • 45
  • 1
  • 4