Divide by 0 Exception - Unofficial reply

You asked the following question in the ROBOTC tech forum. Most forum users cannot answer there, so I’m quoting the question here so others can help

The simple answer to your question is that the cortex does not know how to divide by 0, that’s why you get the exception, the following lines will all potentially cause this to happen.

float rlRatio = 1.0* motor[FR] / motor[BL]; //finding out the ratio of the motor's power
float lrRatio = 1.0* motor[FL] / motor[BR];

float rlEncoderRatio = 1.0*SensorValue[I2C_1] / SensorValue[I2C_2]; // findig out the same motor encoder value ratio
float lrEncoderRatio = 1.0*SensorValue[I2C_4] / SensorValue[I2C_3];

motor[BL], motor[BR], SensorValue[I2C_2] and SensorValue[I2C_3] can all potentially have the value 0.

One way to handle this is with some conditional statements as follows.

float rlRatio;
if( motor[BL] != 0 )
    rlRatio = 1.0* motor[FR] / motor[BL];
    rlRatio = 1; // or whatever makes sense 

Even if you fix the exceptions I’m not sure how well the code will work, the code may be unpredictable under acceleration and deceleration. You also set motor values in more than one place, not a good thing to do (see this bad programming habits post #4).

1 Like

Thanks so much for the help you have no idea how much this mean to me :slight_smile: