-2

I have the following calculation in Java:

rightMotor = (int) (((double)speed)/((double)100)*rightMotor));

Speed and rightMotor are both integers. The problem is, it keeps returning 0. I have tried to force to divide speed and 100 as doubles, which had no different results. Can anyone give me some insight in this?

Thanks in advance.

2 Answers2

2

The reason the calculation returns zero is that the double value computed by the expression is less than one.

It looks like you have placed the parentheses incorrectly - currently, you divide speed by hundred times rightMotor, which is bound to produce a value less than 1.

You need to fix your formula to make it work. If you wanted to compute speed / 100 * rightMotor as if it were a math formula, you could do the multiplication ahead of division, avoiding doubles altogether:

rightMotor = speed * rightMotor / 100;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Since you are assigning the result to an int variable, there's no point in doing floating point division.

rightMotor = speed/(100*rightMotor);

would give you the same result, which would be 0 if speed < 100*rightMotor.

If your intent was to multiply speed/100 by rightMotor, you still don't need to cast to double and then back to int.

Just do:

rightMotor = (speed*rightMotor)/100;
Eran
  • 387,369
  • 54
  • 702
  • 768