Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: New Perl user - help with my homework

by soonix (Canon)
on Dec 24, 2018 at 12:24 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-18 12:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found