简体   繁体   中英

Perl floating point number usage confusion

While using scalar values in perl, I am not able to accomplish the desired results. Need your help in figuring where I am going wrong..

Say I want to loop 9 times and print 0.1 to 0.9

I declared variable $i and using it in for loop as well as inside the loop.

for($i = 1; $i < 10; $i++) 
{
    $b = $ie-01; # (This where I go wrong, I am not sure If I am following correct
                 # syntax here, Because I see -1 getting printed instead of $i value
                 # which is incremented on each loop)
    print "The value now is: $b\n";
}

I do know of different ways to get the desired result but I wanna know how to use exponent to get the desired output. . . . .

Why $i is treated as 0 when used in conjunction with e ?

I think you only forgot to include the multiplication operator * :

$i * 1e-01

The string $ie-01 will be interpreted as $ie - 01 which is an unititialized variable (ie zero) minus one which will give you -1 . (You can use the e -notation only with constant numbers but not with variables.)

Your first mistake was not including:

use strict;
use warnings;

This would have told you about the variable $ie not being declared.

There is no reasonable way to make ${i}e-01 work; you would have to eval it, which is not reasonable. The standard way to write it would be:

$b = $i * 0.1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM