vendredi 21 février 2014

Re: obj 8-2 topic




Marek Novotny <(E-Mail Removed)> writes:
> On Fri, 21 Feb 2014 19:03:10 +0000, Henry Law wrote:


[...]

>> But for an algorithm, why not just loop through the array (Perl is good
>> at that) and keep a running note of the largest number you found?
>>
>> You can code a loop over the values of an array like this:
>>
>> for my $current_number ( @array ) {
>> # Here $current_number is each value in the array,
>> # in order, one by one
>>
>> ... and you can code your 'if' statement more perlishly
>>
>> $max_number = $currentnumber if # Put your condition after the if
>> # and don't forget the semicolon.
>>
>> Then when the loop finishes, print out the maximum number you found.
>> About six lines of code is what you're aiming for.

>
> Thank you for all the replies first of all. I read what you write, but as
> a beginner it's not always easy to translate the information into actual
> code. That being said, this is what I came up with.
>
> #!/usr/bin/perl
> # File: Obj8-2.pl
> use strict;
> use warnings;
>
> my @array=(5,4,3,1,7,23,12,5,43,29,32,18,49);
> my $answer = 0;
> my $elem = 0;
>
> foreach $elem (@array){
> if ($elem > $answer){
> $answer = $elem;
> }
> }
> print "The Answer is: $answer.\n";


This obviously breaks down when the array contains numbers < 0.

@array = (42,41,42,31,54,42,56,57,46,58,59,60,34,61);

$max = $array[0];
$_ > $max and $max = $_ for @array[1 .. $#array];

print "The Answer is: $max\n";





Aucun commentaire:

Enregistrer un commentaire