Is it possible to Write a program that computes averages by asking the user to enter the numbers to be average?
I wrote a perl script that computes the averages of three numbers. Here is my code:
#usr/bin/perl
use strict;
use warnings;
my $a; #variable declaration
my $b; #variable declaration
my $c; #variable declaration
my $avg; #variable declaration
my $x; #variable declaration
my $y; #variable declaration
my $z; #variable declaration
my $results; #variable declaration
my $number; #variable declaration
$a = 2; #number 1
$b = 6; #number 2
$c = 7; #number 3
$avg = avg($a,$b,$c); #Three variables to be averaged
sub avg {
开发者_Python百科 ($x,$y,$z) = @_; #Store variables in array
$results = ($x+$y+$z)/3; #Values stored added, and divided for average
return $results; #return value
}
print "$avg\n";
exit;
Instead of my code computing averages of numbers i enter into variables i rather be prompted to enter three numbers at the terminal to be averaged out. I know in perl to do something like that you have to implement some code like so:
print STDOUT "Enter a number: \n";
$averages = <STDIN>;
print "The Average is $averages.\n";
When i add this to my code it doesn't print anything out how can this be properly implemented to my code.
A more general solution for computing the average could be the first step:
sub avg {
my $total;
$total += $_ foreach @_;
# sum divided by number of components.
return $total / @_;
}
That way you don't care how many items you're averaging. avg()
figures it out.
The next step is to read your input. You can do that with the <>
operator like this:
my @input;
print "Enter a few numbers...\n";
while( <> ) {
chomp;
while( m/([\d.-])/g ) {
push @input, $1;
}
}
local $" = ', ';
print "The average of [@input] is ", avg( @input ), "\n";
And at the end we put it all together by printing the set of inputs, and invoking and printing avg()
.
The regular expression just pulls out things that look vaguely like numbers from a string of input. It's nothing like a number validator.
#!/usr/bin/perl
use warnings;
use strict;
my $sum = 0;
my $n = 0;
while (<>) {
$sum += $_;
$n++;
}
print $sum/$n, "\n";
Briefly, we compute the average by summing and keeping track of the number of items. while (<>)
magically reads either from files specified on the command line or from STDIN (you might want to use while (<STDIN>)
instead if your program is only interactive).
精彩评论