0

i seen to be having a problem with the line:

int xPos = ((x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET; =

for testing purposes i have assigned:

int x = 10;
int maxX = 52;

but when used in this calculation x / maxX gives me 0 instead of 0.19!

http://s12.postimage.org/uawn8b6l9/image.png

1
  • i think X_AXIS_LENGTH and X_AXIS_OFFSET both is zero Commented Mar 1, 2012 at 20:06

4 Answers 4

4

You're doing integer division here:

x / maxX

Integer division will truncate the fractional part.

Cast one of the parameters to floating-point to fix it:

(double)x / maxX

You might also want to store the whole thing into a double instead of int:

double xPos = (((double)x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;
Sign up to request clarification or add additional context in comments.

Comments

1

Both of the operands for / are integers, so it's performing integer arithmetic. Options:

  • Use floating point arithmetic:

    double xPos = (((double) x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;
    
  • Multiply before the division, and you can still do everything in integer arithmetic, although you'll need to beware of overflow:

    int xPos = ((x * X_AXIS_LENGTH) / maxX) + X_AXIS_OFFSET;
    

Comments

0

Integer division did it to you.

If you expect a floating point value, do it this way:

double ratio = ((double)x)/maxX;

That int type all the way though is a problem. I'd put more thought into that. Where do you want to truncate the fractional part?

Comments

0

xPos should be declared as double, not an integer. Otherwise, the data after the decimal point is truncated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.