﹝學習記錄﹞- Perl – 九九乘法表

 

程式1: 列出九九乘法表

陣列 @array

迴圈 foreach 變數( 陣列 ){ 程式碼 }

my @arr1=(1,2,3,4,5,6,7,8,9);  # @arr1=(1..9);

foreach my $num1(@arr1){

  foreach my $num2(@arr1){

    print $num1,"x",$num2,"=",$num1*$num2;

    if ($num2==9){

      print "\n";

    }else{

      print "\t";

    }

  }

}

執行程式範例:

 

程式2: 列出指定的九九乘法表

my $ans='y';

while($ans eq 'y'){  # eq 意指 等於 (用於字元比對)

  #------------------------------------------------------------------

  my @arr1;

  my @arr2;

  # for user input -------------------------------------------------

  print " Please enter column number: ";

  chomp(my $col=<>);

  print " Please enter row number: ";

  chomp(my $row=<>);

  #------------------------------------------------------------------

  @arr1=(1...$row);

  @arr2=(1...$col);

  print "="x72,"\n";

  foreach my $num1(@arr1){

    foreach my $num2(@arr2){

      print " ",$num1,"x",$num2,"=",$num1*$num2,"\t";

    }

    print "\n";

  }

  print "="x72,"\n";

  # for user input --------------------------------------------------

  print " Do you want to input again? (y/n) ";

  chomp($ans=<>);

  if ($ans ne 'y'){

    $ans='n';

  }else{

    print "\n";

  }

  #------------------------------------------------------------------

}

執行程式範例:

 

, , , ,

yunyun 發表在 痞客邦 PIXNET 留言(0) 人氣()