in reply to Floating point number counting script stuck in a loop

Testing floating point numbers for equality (== or !=) is the problem. Instead test using >=, >, < or <=.


Perl is environmentally friendly - it saves trees
  • Comment on Re: Floating point number counting script stuck in a loop

Replies are listed 'Best First'.
Re^2: Floating point number counting script stuck in a loop
by Vonunov (Novice) on Oct 25, 2007 at 07:50 UTC
    I see, thanks. This compiles and runs properly:
    #!/usr/bin/perl $count = .0; while ($count < .9) { $count = $count + .1; print ($count, "\n"); } print ("End!\n");
    But when I use -w and use strict; I get those same compilation errors. What is an explicit package name? What I've found about this error is that it has something to do with having not declared a variable you're trying to use under -w or use strict;, but I've declared my only variable. I don't suppose it especially matters if it compiles at all, but I'm curious now.
      When using strict (which is a good thing), declaring variables happens like this:
      my $count;
      Technically, you've initialised a variable, not declared it. Doing both at the same time:
      my $count = 0.0;
      Update: This link may prove helpful.
      Declaring variables
        Ooh, thanks, that's wonderful. I assumed a variable was declared by being assigned a value in the first place.
        Cheers. :D

      When you use strict; (highly recommended btw.) you need to declare your variables so you need to stick my in front of the first assignment to $count. However, I'd be inclined to use a C type for loop in this case (note the declaration inside the loop header):

      use strict; use warnings; for (my $count = 0.0; $count < 0.9; $count += 0.1) { print "$count\n"; } print "End!\n";

      Note too that print doesn't need () and that variables can be interpolated directly into double quoted strings.


      Perl is environmentally friendly - it saves trees
        Huh, I wonder why the tutorial uses (), then? Do they have any purpose or does it just make things look nice, what with all the rounded-off ends? XD

        Thanks for that, by the way, I've always wanted to be able to compress scripts to be painfully tiny. (No sarcasm, it really does look impressive).

        I did read that variables can be put in strings and I had it that way at the beginning, but I thought it might have been the problem and never changed it back after I tested that.

        Thanks for the help.