-3

How to write a Perl program that adds up the numbers in a file and prints out their sum, average, max and min. There is one number per line. You must print the average out showing two digits after the decimal point.
The numbers are:
50
20
3
4
5

Votes + Comments
Show some effort
Well, ask a stupid question ... We are not a homework service.
4
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by techieinvents
0

I'll do it for you, but I don't think you'll be able to turn it in as your work.

use strict;
use warnings;
use List::Util qw(sum max min);
my @nums=<DATA>;
my $sum=sum(@nums);
my $avg=$sum/@nums;
my $max=max(@nums);
my $min=min(@nums);
print "Sum: $sum\n";
print "Avg: $avg\n";
print "Min: $min\n";
print "Max: $max\n";
__DATA__
50
20
4
3
5

Best to use something someone has already written IMO.

0

Here's the two digits after the decimal point (if zeros matter):

use strict;
use warnings;
use List::Util qw(sum max min);
my @nums=<DATA>;
my $count=@nums;
my $sum=sum(@nums);
my $avg=$sum/$count;
my $max=max(@nums);
my $min=min(@nums);
chomp($min);
print "Sum: $sum\n";
printf "Avg: %0.2f\n",$avg;
print "Min: $min\n";
print "Max: $max\n";

__DATA__
50
20
4
3
5

For some reason list utils seems to return a linefeed (or carriage return) after the min. That's the chomp. I think it's a windows thing, but can't be sure right now.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.