# Where am I dividing by zero?!

``````while(fabs(SensorValue[leftMogoLIftEncoder]) < (mogoLiftGearEncoderValue / (mogoLiftGearRatio)))
{

motor[mogoMotors] = speed * inOrOut;

}
``````

The RobotC compiler is saying I’m diving by zero, but I don’t know why. MogoLiftGearEncoderValue is just a random value the user will put in when using the function and the mogoLiftGearRatio is 12 divided by 60 (12 tooth gear to a 60 tooth gear). Where am I dividing by zero?

1. Show us the declaration of mogoLiftGearRatio. Is it declared as an int? If so, it might be truncating to 0.

2. It could be something wrong with an operation you’re doing in

``````
fabs()

``````

.

If mogoLiftGearRatio is declared an an integer then ROBOTC will understand that it will be zero as 12/60 will round down. ie. when the result of the calculation, 0.2, is converted to an int it will become 0.

Integer math in C (including RobotC):

Dividing an integer by an integer will not produce fractions, even if normal math would, i.e. the quotient will always be truncated (rounded downwards, essentially “cutting off” a decimal). Say you divide 3 by 2. Ideally, you should get 1.5, but the way C works with integers, that same operation would result in 1, not 1.5. In your case, you’re dividing 12 by 60 and plugging that into a integer variable. Because integer variables don’t have decimals, the C compiler will interpret that as being 0, not 0.2, which is where the zero is coming from. It’s not an error of yours, just the way the C language behaves, specifically in the very nature of int and float data types. To fix that, I suggest using floats instead of ints.

However, if you do 3.0/2 or 3/2.0, the compiler will (“correctly”) read that as 1.5.

I should have clarified that I’m using floats.

Try casting like so:

``````
while(fabs(SensorValue[leftMogoLIftEncoder]) < ((float)mogoLiftGearEncoderValue /(float)(mogoLiftGearRatio)))

``````

just to see what happens…

Is the math of 12/60 written as 12/60 OR 12.0/60.

12/60 is 0
12.0/60 is 0.2

It’s “12 / 60;” exactly. What’s in the quotations is exactly what I have for the code. I found a temporary solution where I put the simplified value, so 0.2. It stills boggles me that I can’t have a simple expression. The reason I would like an expression being my other team members need to be able to read the code and input the right values, and they can definitely see what 12 / 60 means (it’s a 5 torque ratio). But they won’t be able to identify 0.2 as quickly.

Not to be mean, but isn’t that what comments are supposed to help with?

Try assigning “12.0/60” or a variation thereof to your variable. The reason why all this is happening is due to the phenomenon of type conversion.

So when c does math the output of the math is the largest type of the 2 inputs.
12/60 are both ints so it will output an int, which obviously 0.2 becomes 0.

Thats why I said

12/60 is 0
12.0/60 is 0.2

12.0 forces the math to be float /int which outputs a float.