Why not the same result?

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!

Moderators: Pete, Mods

Post Reply
nyfiken
Newbie
Posts: 7
Joined: Sun Aug 26, 2007 11:57 pm

Why not the same result?

Post by nyfiken »

I?m confused about these few lines. Does anyone know why the number
20070501 becomes 20070500 in the last kolumn?

Code: Select all

CLS

number$ = "20070501"
PRINT number$;
day$ = LEFT$(number$, 8)
PRINT USING " ########"; VAL(day$);
day = VAL(LEFT$(number$, 8))
PRINT USING " ########"; day
The output is:
20070501 20070501 20070500



If I change number$ to "20070502" then the three kolums will be the same, 20070502 20070502 20070502.

:?:
________
HOT BOX VAPORIZER
Last edited by nyfiken on Tue Feb 15, 2011 10:32 pm, edited 1 time in total.
Anonymous

Post by Anonymous »

Hi,

Because you are using such a large number when you day = VAL(LEFT$(number$, 8)) qbasic makes day an integer which only goes up to 32768, so if you dim day as a long it will work.

Code: Select all

CLS

number$ = "20070501"
PRINT number$;
day$ = LEFT$(number$, 8)
PRINT USING " ########"; VAL(day$);
dim day2 as long
day2 = VAL(LEFT$(number$, 8))
PRINT USING " ########"; day2 
Mac
Veteran
Posts: 151
Joined: Mon Aug 06, 2007 2:00 pm

Post by Mac »

Nixon wrote:Because ...blah, blah
Good answer!!

Mac
nyfiken
Newbie
Posts: 7
Joined: Sun Aug 26, 2007 11:57 pm

Post by nyfiken »

Interesting, I thought QB was 100% safe regarding variables, that it generated some kind of oveflow error when the numbers were out of limit. Newertheless it's no problem if one knows about it. Thanks!
________
Bmw V5
Last edited by nyfiken on Tue Feb 15, 2011 10:32 pm, edited 1 time in total.
Nodtveidt
Veteran
Posts: 826
Joined: Sun Jul 25, 2004 4:24 am
Location: Quebradillas, PR
Contact:

Post by Nodtveidt »

It's a floating point conversion error. day is going to be SINGLE by default. VAL is irrespective of numeric type; it will return a value that fits into the data type you use with the function.

Try using PRINT day at the end of your program...you'll get an interesting result that confirms the conversion error. It's a fault with floating point values.

As a general rule, you should always DIM your variables before you use them, especially in QB where all variables are SINGLE by default.
Post Reply