Re: [問題] 問一下哪裡語法錯誤?
※ 引述《gigantic30 (gigantic30)》之銘言:
: 這是我第一次寫perl, 請板上高手指點一下
: 謝謝^^
: %h=(fib(0)=>1, fib(1)=>1);
: sun fib
: {
: $h{fib($_[0])} = fib($_[0]-1)+fib($_[0]-2);
: return $h{fib($_[0])};
: }
: print "Enter an integer>=0: ";
: $n=<stdin>;
: $ans=fib($n);
: print "The $nth Fibonacci number is $ans";
: print "\nBelow is the hash table created during the computation.\n"
: foreach (keys %h){
: print "$_=>$h{$_}\n";
: }
#!/usr/bin/perl
#%h=(fib(0)=>1, fib(1)=>1);
%h=(0 => 0, 1 => 1);
#sun fib
sub fib
{
return $h{$_[0]} if($_[0] == 0 or $_[0] == 1);
# $h{fib($_[0])} = fib($_[0]-1)+fib($_[0]-2);
$h{$_[0]} = fib($_[0] - 1) + fib($_[0] - 2);
# return $h{fib($_[0])};
return $h{$_[0]};
}
print "Enter an integer>=0: ";
#$n=<stdin>;
chomp($n=<stdin>);
die "Error!\n" if($n < 0);
$ans=fib($n);
print "The $nth Fibonacci number is $ans";
#print "\nBelow is the hash table created during the computation.\n"
print "\nBelow is the hash table created during the computation.\n";
#foreach (keys %h){
foreach (sort { $a <=> $b } keys %h){
# print "$_=>$h{$_}\n";
print $_ . ' ' x (length($n) - length($_)) . ' => ' . $h{$_} . "\n";
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.232.236.185
※ 編輯: giacch 來自: 118.232.236.185 (10/08 00:56)
→
10/08 00:58, , 1F
10/08 00:58, 1F
# sub fib 改良...
%h=(0 => 0, 1 => 1);
sub fib {
return $h{$_[0]} if($_[0] == 0 or $_[0] == 1);
for($i = 2; $i <= $_[0]; $i ++) { $h{$i} = $h{$i - 1} + $h{$i - 2}; }
return $h{$_[0]};
}
※ 編輯: giacch 來自: 118.232.236.185 (10/08 01:05)
→
10/08 01:15, , 2F
10/08 01:15, 2F
推
10/08 01:48, , 3F
10/08 01:48, 3F
→
10/08 01:54, , 4F
10/08 01:54, 4F
討論串 (同標題文章)