看板 Perl 關於我們 聯絡資訊
※ 引述《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)
giacch:我輸入100然後就... XDDD 10/08 00:58
# 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)
giacch:有些地方原本沒有錯誤... 是我手賤硬是要改... orz 10/08 01:15
gigantic30:感謝! 再請問一下chomp是? 10/08 01:48
giacch:刪除結尾換行字元... 10/08 01:54