Re: [問題] 問一下哪裡語法錯誤?

看板Perl作者 (小a)時間15年前 (2008/10/08 00:51), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《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
我輸入100然後就... XDDD
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
有些地方原本沒有錯誤... 是我手賤硬是要改... orz
10/08 01:15, 2F

10/08 01:48, , 3F
感謝! 再請問一下chomp是?
10/08 01:48, 3F

10/08 01:54, , 4F
刪除結尾換行字元...
10/08 01:54, 4F
文章代碼(AID): #18wvEJ_w (Perl)
文章代碼(AID): #18wvEJ_w (Perl)