Page 1 of 1

Newbie question Difference between 2 numbers

Posted: Sat Jan 12, 2008 10:23 am
by PeterGams
How can I find the difference between to numbers?
I need to make sure there is no greater difference then 7 between two numbers.
Sometimes the first number will be less then the first. eg a=1 b=9.
Other times the reverse. eg a=9 b =1.
I don't want the result to be a negative one.

Sorry for the newbie question but I keep getting negative numbers.

Re: Newbie question Difference between 2 numbers

Posted: Sat Jan 12, 2008 10:27 am
by PB
Use the Abs() command to prevent negatives:

Code: Select all

a=1 : b=9 : Debug Abs(a-b)
a=9 : b=1 : Debug Abs(a-b)

Posted: Sat Jan 12, 2008 10:32 am
by Hroudtwolf
Hi,

Code: Select all

Procedure Greater7 (a,b)
   If (a > b)
      If (a - b) > 7
         ProcedureReturn #True
      EndIf
   Else
      If (b - a) > 7
         ProcedureReturn #True
      EndIf
   EndIf
   ProcedureReturn #False
EndProcedure

If Greater7 (10,17)
   Debug "Alert: Greater difference than 7."
EndIf

If Greater7 (10,18)
   Debug "Alert: Greater difference than 7."
EndIf

If Greater7 (2,10)
   Debug "Alert: Greater difference than 7."
EndIf

Thanks Heaps Guys

Posted: Sat Jan 12, 2008 10:45 am
by PeterGams
The ABS seems to woork great.
Best of all it is easier than I thought.

Thanks Again. :D

Re: Thanks Heaps Guys

Posted: Sat Jan 12, 2008 10:50 am
by gnozal
PeterGams wrote:The ABS seems to woork great.
Best of all it is easier than I thought.
Please note that Abs() should only be used for floats, not integers !
From the manual : "This function works correctly only with float numbers. With integer it will fail if the integer is too big (loss of precision)."

Posted: Sat Jan 12, 2008 12:11 pm
by AND51
@ PeterGams:
Here is a very simple procedure:

Code: Select all

Procedure Difference(no1, no2, maxDifference=7)
	If no1 < no2
		Swap no1, no2
	EndIf
	If no1-no2 > maxDifference
		ProcedureReturn #True
	EndIf
EndProcedure

Debug Difference(4, 9)
Debug Difference(9, 1)
Debug Difference(7, 5, 1)
You can easily define the 'maxDifference' on-the-fly (leave the 3rd parameter blank if you want it to be 7).

With this code I want to show you some commands that might be useful for you. You can increase the performance and readability of you code, if you compare my code to Hroudtwolf's one. So don't be afraid when being confronted with optional parameters or PureBasic keywords like Swap (quickly swaps the content of two elements).
Happy coding! :D

Posted: Sat Jan 12, 2008 12:40 pm
by #NULL
just for fun 8)

Code: Select all

Macro diff(a,b)
  (  ((a)-(b)) + (0 Or (b)>(a))*-2*((a)-(b))  )
EndMacro

Debug diff(8,8)  ; 0
Debug diff( 4,6) ; 2
Debug diff(13,9) ; 4
Debug diff(-3,2) ; 5

Posted: Sat Jan 12, 2008 3:34 pm
by Baldrick