⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fig05_05.pl

📁 PERL语言资料 可以用于PERL程序设计
💻 PL
字号:
#!/usr/bin/perl
# Fig. 5.5: fig05_05.pl
# Survey data analysis: Determining the mean, median and mode.

@opinions = ( 8, 9, 4, 7, 8, 5, 6, 4, 9, 9, 
              7, 8, 9, 5, 4, 8, 7, 8, 7, 7, 
              6, 6, 8, 9, 1, 9, 8, 7, 8, 7,
              7, 8, 9, 8, 9, 4, 9, 6, 8, 4,
              6, 7, 3, 4, 8, 7, 9, 8, 9, 2  );

# determine the mean
$total = 0;

foreach ( @opinions ) {
   $total += $_;
}

$mean = $total / @opinions;
print "Survey mean result:   $mean\n";

# determine the median
@sorted = sort { $a <=> $b } @opinions;
$middle = @sorted / 2;    # middle element subscript

# for an even number of elements, average the two middle 
# elements to determine the median; otherwise, use the 
# middle element
if ( @sorted %2 == 0 ) {  # even number of elements
   $median = 
      ( $sorted[ $middle - 1 ] + $sorted[ $middle ] ) / 2;
}
else {                    # odd number of elements
   $median = $sorted[ $middle ];
}

print "Survey median result: $median\n";

# determine the mode
$mode = 0;

foreach ( @opinions ) {
   ++$frequency[ $_ ];     # increment the frequency counter
   
   # if the current frequency is greater than the $mode's 
   # frequency, change $mode to $_
   if ( $frequency[ $_ ] > $frequency[ $mode ] ) {
      $mode = $_;
   }
}

print "Survey mode result:   $mode\n\n";

# display a frequency graph
print "Response\tFrequency\n";
print "--------\t---------\n";

foreach ( 1 .. 9 ) {
   print "$_\t\t", "*" x $frequency[ $_ ], "\n";
}


###########################################################################
#  (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall.     #
#  All Rights Reserved.                                                   #
#                                                                         #
#  DISCLAIMER: The authors and publisher of this book have used their     #
#  best efforts in preparing the book. These efforts include the          #
#  development, research, and testing of the theories and programs        #
#  to determine their effectiveness. The authors and publisher make       #
#  no warranty of any kind, expressed or implied, with regard to these    #
#  programs or to the documentation contained in these books. The authors #
#  and publisher shall not be liable in any event for incidental or       #
#  consequential damages in connection with, or arising out of, the       #
#  furnishing, performance, or use of these programs.                     #
###########################################################################

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -