Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Perl (http://www.programmingforums.org/forum21.html)
-   -   A simple script isn't working correctly (http://www.programmingforums.org/showthread.php?t=7690)

scuzzman Dec 23rd, 2005 5:29 AM

A simple script isn't working correctly
 
I'm having trouble getting a very simple script to run and cannot figure out the problem. The script is as follows:
:

#!/usr/bin/perl -w

$level = 1;
$prod = (20 * $level) * (1.1 ** $level);

print "What is the amount of energy you\'re trying to accumulate? ";
chomp ( $goal = <STDIN> );

while ($prod <= $goal) {
  # print "$level\n"; # DEBUG: print the current level
  $level++;
}

print "\nRequired level for $goal energy from a solar planet is $level\n";

The problem is that the $prod never changes from 22 (which is what it evaluates to when $level = 1). Because $prod is based on the value of $level, shouldn't $prod change when $level does?

Arevos Dec 23rd, 2005 5:43 AM

Quote:

Originally Posted by scuzzman
Because $prod is based on the value of $level, shouldn't $prod change when $level does?

No. And this is common in computer languages. The code:
:

$a = 2;
$b = 3;
$c = $a + $b;

Adds together the value of $a and $b, and puts the resulting number in $c. This value is static, because it's just a number.

In order to change the value, you need to perform the calculation again:
:

$b = 4;
$c = $a + $b;


scuzzman Dec 23rd, 2005 5:57 AM

Thanks! Would changing this to a constant achieve my desired result, or would I need to just write a subfunction to repeatedly do the calculation?

Arevos Dec 23rd, 2005 6:42 AM

Quote:

Originally Posted by scuzzman
Thanks! Would changing this to a constant achieve my desired result, or would I need to just write a subfunction to repeatedly do the calculation?

A subroutine sounds your best bet:
:

sub findProd {
    my $level = shift @_;
    return (20 * $level) * (1.1 ** $level);
}

...

$level++ while (findProd($level) <= $goal);



All times are GMT -5. The time now is 5:18 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC