in reply to oldschool math

pretty cool, 2 comments:
  1. you should try to get this working with -w/strict
  2. you seem to have some "carry" problems...
    $a = '99999999999999999999999999999999999'; $b = '1'; print " $a\n+ $b\n= ", add($a, $b);

    Gives...

    99999999999999999999999999999999999 + 1 = 00000000000000000000000000000000000
(perhaps #1 would help to solve #2 ?)

Replies are listed 'Best First'.
Re: Re: oldschool math
by PerpLexicon (Novice) on Jul 02, 2002 at 19:09 UTC
    The problem doesn't seem to be the -w, but rather that $In_Mente is forgotten. -w is always complaining about uninitialized-whatsoever, so we'll just have to make some precautions:

    sub add($$) { my ($Val1, $Val2) = @_; my ($Result, $Tmp) = ('',0); my $In_Mente = ''; (length($Val1) < length($Val2)) ? ($Val1, $Val2)=($Val2, $Val1):0; while (length($Val2) || length($Val1)) { $Tmp = substr($Val1,-1,1); $Tmp += substr($Val2, -1, 1) if (length($Val2)); $Tmp += $In_Mente if (length($In_Mente)); if ($Tmp > 9) { $In_Mente = 1; $Tmp -= 10;} else { $In_Mente = ''; } $Result = $Tmp . $Result; substr($Val1, -1, 1) = ''; substr($Val2, -1, 1) = ''; my $FResult = $Result; last if ($In_Mente eq '' && !length($Val2)); } $Result = $In_Mente . $Result; $Result = $Val1 . $Result; return $Result; } $a = '99999999999999999999999999999999999999999999'; $b = '1'; print " $a\n+ $b\n= ", add($a, $b);

    Prints out:
    99999999999999999999999999999999999999999999 + 1 = 100000000000000000000000000000000000000000000