norbdum
norbdum

Reputation: 2491

Perl:Error in increment

I am trying to increase three numb 3,4,6 from num+0.1 to num+0.7 all numbers are working fine except 3. Why?

foreach my $num(3,4,6){

    for(my $state=$num+0.1;$state<=$num+0.7;$state+=0.1){
            print $state."\n";
    }

}

Output: enter image description here This continues even if I hardcode and print only till 3.6.

for(my $state=3;$state<=3.7;$state+=0.1){
        print $state."\n";
}

Upvotes: 2

Views: 63

Answers (2)

Kenosis
Kenosis

Reputation: 6204

Here's another option:

use strict;
use warnings;

for my $num ( 3, 4, 6 ) {
    for my $i ( 1 .. 7 ) {
        print $num + $i / 10, "\n";
    }
}

Output:

3.1
3.2
3.3
3.4
3.5
3.6
3.7
4.1
4.2
4.3
4.4
4.5
4.6
4.7
6.1
6.2
6.3
6.4
6.5
6.6
6.7

Upvotes: 1

Filippo Lauria
Filippo Lauria

Reputation: 2064

Use Math::BigFloat;

like this:

#!C:/path/of/perl.exe -w

use Math::BigFloat ':constant';

use warnings;
use strict;

foreach my $num(3,4,6) {

    for(my $state=$num+0.1;$state<=$num+0.7;$state+=0.1){
            print $state."\n";
    }    
}

Output:

3.1
3.2
3.3
3.4
3.5
3.6
3.7
4.1
4.2
4.3
4.4
4.5
4.6
4.7
6.1
6.2
6.3
6.4
6.5
6.6
6.7

Upvotes: 1

Related Questions