Q(uick)BASIC Function: SGN
Quick View
SGN
A math function that indicates the sign 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
- SGN(numeric-expression)
Description/Parameter(s)
- If numeric-expression is positive, the SGN function returns +1.
- If numeric-expression is zero, the SGN function returns 0.
- If numeric-expression is negative, the SGN function returns -1.
Example
The following program calculates and prints the solution for the input quadratic (or second-degree) equation. The program uses the sign of a test expression to determine how to calculate the solution.
CONST NoRealSoln=-1, OneSoln=0, TwoSolns=1
' Input coefficients of quadratic equation:
' ax^2 + bx + c = 0.
INPUT;"a = ", A
INPUT;", b = ",B
INPUT ", c = ",C
Test = B^2 - 4*A*C
SELECT CASE SGN(Test)
CASE NoRealSoln
PRINT "This equation has no real-number solutions."
CASE OneSoln
PRINT "This equation has one solution: ";
PRINT -B/(2*A)
CASE TwoSolns
PRINT "This equation has two solutions: ";
PRINT (-B + SQR(Test))/(2*A) " and ";
PRINT (-B - SQR(Test))/(2*A)
END SELECT
Sample Output:
This equation has two solutions: .6666667 -.25Syntax
- SGN(numeric-expression)
Description/Parameter(s)
- If numeric-expression is positive, the SGN function returns 1.
- If numeric-expression is zero, the SGN function returns 0.
- If numeric-expression is negative, the SGN function returns -1.
Example
This example calculates and prints the solution for the input quadratic (or second-degree) equation. The program uses the sign of the discriminant returned by the SGN function to determine how to calculate the solution.
CONST NoRealSoln = -1, OneSoln = 0, TwoSolns = 1
'Input coefficients of quadratic equation:
'ax^2 + bx + c = 0.
INPUT ; "a = ", A
INPUT ; ", b = ", B
INPUT ", c = ", C
Discriminant = B ^ 2 - 4 * A * C
SELECT CASE SGN(Discriminant)
CASE NoRealSoln
PRINT "This equation has no real-number solutions."
CASE OneSoln
PRINT "This equation has one solution: ";
PRINT -B / (2 * A)
CASE TwoSolns
PRINT "This equation has two solutions: ";
PRINT (-B + SQR(Discriminant)) / (2 * A); " and ";
PRINT (-B - SQR(Discriminant)) / (2 * A)
END SELECT
Sample Output:
a = 3, b = -4, c = 1 This equation has two solutions: 1 and .3333333See also: