avoiding error when dividing by 0

LiveCode is the premier environment for creating multi-platform solutions for all major operating systems - Windows, Mac OS X, Linux, the Web, Server environments and Mobile platforms. Brand new to LiveCode? Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller

Post Reply
ac11ca
Posts: 41
Joined: Sun Mar 16, 2008 2:22 am

avoiding error when dividing by 0

Post by ac11ca » Tue Jan 20, 2009 8:06 am

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

Mark
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 5150
Joined: Thu Feb 23, 2006 9:24 pm
Contact:

Post by Mark » Tue Jan 20, 2009 11:23 am

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
The biggest LiveCode group on Facebook: https://www.facebook.com/groups/livecode.developers
The book "Programming LiveCode for the Real Beginner"! Get it here! http://tinyurl.com/book-livecode

mwieder
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 3581
Joined: Mon Jan 22, 2007 7:36 am
Contact:

Post by mwieder » Tue Jan 20, 2009 11:02 pm

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

ac11ca
Posts: 41
Joined: Sun Mar 16, 2008 2:22 am

Post by ac11ca » Thu Jan 22, 2009 5:59 am

Thanks Mark. And clever mwieder :)

Post Reply