Page 1 of 1

avoiding error when dividing by 0

Posted: Tue Jan 20, 2009 8:06 am
by ac11ca
Hi there,

I have some coding that divides a value (p) by a counting variable (q), i.e., "divide p by q". Sometimes when the user doesnt click on a certain button that they are meant to, the counting variable is still at zero when the command runs and therefore I get an error because I am trying to divide by zero.

Is there some sort of quick trick I can do that automatically returns a value of zero whenever I try to divide by zero? If there isnt, I guess I will have to create some kind of if...then... command that checks that the counting variable is not at zero.

Cheers,
Ac

Posted: Tue Jan 20, 2009 11:23 am
by Mark
Hi Ac,

Probably, you need to add an error message, such as

Code: Select all

 if q is 0 then
  beep
  answer error "Click the button first!"
else
  -- go ahead
end if
If you really want y=p/q to be 0 if q is 0 then you can write a script such as

Code: Select all

if q = 0 then
  put 0 into y
else
  put p/q into y
  -- go ahead
end if
Best,

Mark

Posted: Tue Jan 20, 2009 11:02 pm
by mwieder
For a simple situation like this, I'd go with Mark's answer. But just for fun, and to show that there are many ways to approach any given problem, the following code does the same thing:

Code: Select all

try
  put p/q into y
catch e
  put 0 into y
end try
--go ahead

Posted: Thu Jan 22, 2009 5:59 am
by ac11ca
Thanks Mark. And clever mwieder :)