Q(uick)BASIC Function: ABS
Quick View
ABS
A math function that returns the absolute value of a numeric expression
Worth knowing
Useful and cross-version information about the programming environments of QBasic and QuickBasic.
Syntax
- ABS(numeric-expression)
- SGN(numeric-expression)
Description/Parameter(s)
numeric-expression | Any numeric expression. |
Example
PRINT ABS(45.5 - 100!) 'Output is: 54.5
PRINT SGN(12), SGN(-31), SGN(0) 'Output is: 1 -1 0
Syntax
- ABS(numeric-expression)
Description/Parameter(s)
The absolute value is the unsigned magnitude of the argument. For example, ABS(-1) and ABS(1) are both 1.
Example
The following example finds an approximate value for a cube root. It uses ABS to find the difference between two guesses to see if the current guess is accurate enough.
DEFDBL A-Z
Precision = .0000001#
CLS 'Clear the screen
INPUT "Enter a value: ", Value 'Prompt for input
' Make the first two guesses.
X1 = 0.0# : X2 = Value
' Go until the difference between two guesses is
' less than the required precision.
DO UNTIL ABS(X1 - X2) < Precision
X = (X1 + X2) / 2.0#
' Adjust the guesses.
IF X * X * X - Value < 0.0# THEN
X1 = X
ELSE
X2 = X
END IF
LOOP
PRINT "The cube root is "; X
Sample Output:
Enter a value: 27 The cube root is 2.999999972060323Syntax
- ABS(numeric-expression#)
Description/Parameter(s)
The absolute value is the unsigned magnitude of the argument. For example, ABS(-1) and ABS(1) are both 1.
Example
This example finds the cube root of an input value. It uses the ABS function to test if the current guess is accurate. The DEFDBL statement is used to establish the default for the variables.
DEFDBL A-Z
Precision = .0000001#
CLS 'Clear the screen.
INPUT "Enter a value: ", Value 'Prompt for input.
'Make the first two guesses.
X1 = 0#: X2 = Value
'Loop until the difference between guesses is
'less than the required precision.
DO UNTIL ABS(X1 - X2) < Precision
X = (X1 + X2) / 2#
' Adjust the guesses.
IF X * X * X - Value < 0# THEN
X1 = X
ELSE
X2 = X
END IF
LOOP
PRINT "The cube root is "; X
Sample Output:
Enter a value: 27 The cube root is 2.99999997206032See also: