Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: New Perl user - help with my homework

by soonix (Abbot)
on Dec 24, 2018 at 12:24 UTC ( #1227654=note: print w/replies, xml ) Need Help??

in reply to New Perl user - help with my homework

print "Please enter a number: \n"; my ($limit)= <STDIN>; chomp $limit; my $sum = 1; my @array = (); for (my $i=1; $i<=$limit; $i+=2) { $sum += 2 push(@array,'1') } my $average = $sum/scalar(@array); print "$average\n";
  • Syntax terror: there's a semicolon missing between $sum += 2 and push(@array,'1'). Most of us would end push(@array,'1'); with a semicolon, too.
  • Context: my ($limit) indicates "list context", which forces you to explicitly enter an EOF after your input. A very good explanation to this topic is in Modern Perl by chromatic, here, but I recommend reading the complete book, eventually.
    Here, it should be my $limit = <STDIN>; without the parens.
  • Algorithm: You are computing the average of n times 2, and you calculate it wrong. I recommend that you put
    print "i: $i, sum: $sum, array: @array, scalar: ", scalar(@array), "\n +";
    after the push (which means you need the aforementioned semicolon) to see what is going on:
  • The sum has to start with zero, not with one.
  • You have to add $i, not a constant of two.
  • You should push $i instead of '1'

Replies are listed 'Best First'.
Re^2: New Perl user - help with my homework
by Eardrum (Initiate) on Dec 24, 2018 at 14:53 UTC
    Hey, and thank you all for your help. I appreciate it. I have edited my original message, if you could take a look, I'd much appreciate it. Thank you!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1227654]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (14)
As of 2019-05-20 13:19 GMT
Find Nodes?
    Voting Booth?
    Do you enjoy 3D movies?

    Results (128 votes). Check out past polls.