This is because you increment $total before putting anything into the corresponding index of @value.
The simplistic fix would be to do an additional $total--; But you will need to divide by $total+1 (Number of elements).
I think the main issue is that you expect $total to be both an index, and a count of number of values.
There are numerous other coding style suggestions - I'm sure others will chime in.
Update: Here is a simplistic, more perlish rewrite of your code, including some error checking.
#!/usr/bin/perl use strict; use warnings; print "\nMean Average Program\n\nenter values, when done enter 'done': +"; my @value; while (my $input=<>){ chomp $input; last if uc($input) eq "DONE"; #Validate that the input is only digits-should reallly [use Scalar:: +Util qw(looks_like_number)] print ("INVALID value '$input' -ignored\nTry again:") , next unless $input =~ /^[+-]?\d+(\.\d+)?$/; # Crude floating-point +test push @value, $input ; print "Enter a value('done' if finished): "; } my $mean = 0; for my $val (@value){ $mean += $val; } if (scalar @value){ # There is at least one @value - avoid div by 0 $mean = $mean / scalar(@value); } print "\nThe mean of your values is $mean\n";
Theory is when you know something, but it doesn't work.
Practice is when
something works, but you don't know why it works.
Programmers combine Theory
and Practice: Nothing works and they don't know why.
-Anonymous
In reply to Re: Use of uninitialized value in addition
by NetWallah
in thread Use of uninitialized value in addition
by Solarplight
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |