Search code examples
perldivide-by-zero

Illegal division by zero


@xyVal = (4,4,6,6,10,12,18,22,24,28,30);
@yVal = (176,178,180,184,192,202,210,218,224,232,238);

@xxVal = (9,9,9,9,9 ,11,13,15,17,19,19);
@xVal = (168,166,164,162,158,150,142,134,122,116,110);

for ($i = 0; $i <  scalar(@xVal); $i++){
    for ($i = 0; @xyVal[$i] < @xxVal[$i]; $i++){
        @yNewVal = @yVal[$i-1] + (@yVal[$i] - @yVal[$i-1])*(@xxVal[$i] - @xyVal[$i-1])/(@xyVal[$i] - @xyVal[$i-1]);
    }
}
print @yNewVal;

I understand why its giving me the error Illegal division by zero about line 9 (the @yNewVal = ...)

I want the array to have 0 in it if there is a division between zeros. What am I doing wrong? So, how can I avoid that my application crashes when there is a division by zero?


Solution

  • Your divisor on that line is @xyVal[$i] - @xyVal[$i-1], so any case where you have two identical adjacent values in @xyVAl (e.g. 4,4) will result in a 0, and thus a divide-by-zero error.