For loop

1. Member
Join Date
Dec 1969
Posts
52

## For loop

I am trying to display number in a particular sequence <BR>for eg if fstart=2 and fend=6 and inc=2 then the sequence should be 2,4,6<BR><BR>I am having trouble generating the sequence when fstart=9.2<BR>fend=8.6 and inc=0.3<BR>I am using for loop as below<BR><BR>&#060;%<BR>fstart=9.2<BR>fend=8.6<BR> inc=0.3<BR>for i=fstart to fend step -inc<BR> Response.Write i<BR>next<BR>The sequence that is displayed is 9.2 8.9 <BR>The correct sequence would be 9.2 8.9 8.6<BR><BR>I dont know where the problem is and how to address it .<BR>Thanks for help<BR>Ken<BR><BR>

2. Senior Member
Join Date
Dec 1969
Posts
96,118

## The inexactness of decimal numbers...

...in computers is well documented.<BR><BR>What is happening is that when you start with 9.2 and subtract 0.3 from it twice, you are ending up with a number that is just the TINIEST BIT under 8.6 --- perhaps 8.59999999999<BR><BR>But, still, it *is* less than 8.6, so the FOR...NEXT logic says "Nope, gone too far."<BR><BR>Using an increment that is not an integer is just an invitation to this kind of problem.<BR><BR>A slightly hacky solution is to simply change the limit by a a portion of the incrementor. That is, when decrementing as you are:<BR> FOR i = fstart To fend-0.1*inc Step -inc<BR><BR>Or, when going forward<BR> For i = fstart To fend+0.1*inc Step inc<BR><BR>(Obviously, anything up to 0.5*inc should work just fine, by definition.)<BR><BR>

3. Member
Join Date
Dec 1969
Posts
52

## RE: The inexactness of decimal numbers...

Thanks It worked

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•