作者giacch (小a)
看板Perl
标题Re: [问题] 问一下哪里语法错误?
时间Wed Oct 8 00:51:30 2008
※ 引述《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)
1F:→ 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)
2F:→ giacch:有些地方原本没有错误... 是我手贱硬是要改... orz 10/08 01:15
3F:推 gigantic30:感谢! 再请问一下chomp是? 10/08 01:48
4F:→ giacch:删除结尾换行字元... 10/08 01:54