Mac found some more bugs in the above code. Numbers starting with 0 or with -0 are flagged as non-numbers. Such strings entered as negative real numbers or as positive serial numbers should be valid. Also, decimal numbers ending with 0 should also be valid.
I added extra code in the function between the IF UCASE$ line and the stnum$ = LTRIM$ line. I also changed the arguments in the main program to pass by value since snum$ is changed by the function.
The altered code may now be longer than the original version, but here it is:
=======================================================
DECLARE FUNCTION IsNumber% (snum$, real)
DIM snum AS STRING
CLS : INPUT "Enter a real number: ", snum$
IF IsNumber%((snum$), 1) THEN
PRINT snum$; " is a real number."
PRINT "The numeric value is: "; VAL(snum$)
ELSE
PRINT snum$; " is NOT a real number."
END IF
PRINT : INPUT "Enter a positive integer: ", snum$
IF IsNumber%((snum$), 0) THEN
PRINT snum$; " is a number."
PRINT "The numeric value is: "; VAL(snum$)
ELSE
PRINT snum$; " is NOT a positive integer."
END IF
END
FUNCTION IsNumber% (snum$, real)
CONST FALSE = 0, TRUE = NOT FALSE
DIM num AS DOUBLE, stnum AS STRING
DIM x AS INTEGER, s AS INTEGER, nnum AS STRING
IF UCASE$(snum$) <> LCASE$(snum$) THEN EXIT FUNCTION
IF LEFT$(snum$, 1) = "-" THEN
snum$ = MID$(snum$, 2)
s = 1
END IF
N = LEN(snum$)
nnum$ = snum$
FOR x = 1 TO N
IF MID$(snum$, x, 1) = "0" THEN
nnum$ = MID$(snum$, x + 1)
ELSE
EXIT FOR
END IF
NEXT x
snum$ = nnum$
IF s = 1 THEN snum$ = "-" + snum$
IF real THEN
num = VAL(snum$)
N = LEN(snum$)
FOR x = N TO 1 STEP -1
IF RIGHT$(nnum$, 1) = "0" THEN
nnum$ = MID$(snum$, 1, x - 1)
ELSE
EXIT FOR
END IF
NEXT x
snum$ = nnum$
ELSE
num = INT(ABS(VAL(snum$)))
END IF
stnum$ = LTRIM$(STR$(num))
IF snum$ = stnum$ THEN
IsNumber = TRUE
ELSE
IsNumber = FALSE
END IF
END FUNCTION
This message has been edited by Solitaire1 on Apr 2, 2006 3:28 PM This message has been edited by Solitaire1 on Apr 1, 2006 7:47 PM This message has been edited by Solitaire1 on Apr 1, 2006 4:01 PM This message has been edited by Solitaire1 on Apr 1, 2006 3:49 PM This message has been edited by Solitaire1 on Apr 1, 2006 3:32 PM
|
|