CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2008
    Posts
    43

    Perl - Finding the Smallest Number

    I am learning Perl and I am currently doing a program where it should read a list of numbers, sort and print the numbers, find the sum, largest, smallest and average number. It should also compute the standard deviation.

    Currently my program works but when I add the last line to find the smallest number I get the following error:
    syntax error at math.pl line 58, near "print"
    Execution of math.pl aborted due to compilation errors.

    Can I not use that syntax to print the first number in the sorted array.

    Code:
    #!/usr/bin/perl 
    
    
    # get array size 
    print ("How many items?\n"); 
    $size = <STDIN> ; 
    chomp ($size); 
    
    # get array values 
    for ($x=0; $x<$size; $x++) 
    { 
    	print ("Enter number\n"); 
    	$val = <STDIN> ; 
    	chomp ($val); 
    	$data[$x] = $val; 
    } 
    
    # print array values 
    print ("Here is what you entered: \n"); 
    for ($x=0; $x<$size; $x++) 
    { 
    	print ("$data[$x]\n"); 
    } 
    
    #Finding the Sum
    my $total = 0; 
    ($total+=$_) for @data; 
    print "The sum is $total\n";
    
    #Finding the Average
    $average=$total/$size;
    print "The average is $average\n";
    
    #Finding the Standard Deviation 
    #find the mean of the squares of the differences between each number and the average
    my $total2 = 0;
    foreach my $x (@data) {
    	$total2 += ($x-$average)**2;
    }
    my $mean2 = $total2 / $size;
    
    #Take the square root to find standard deviation
    my $std_dev = sqrt($mean2);
    print $std_dev;
    
    #Sorting the array of numbers
    @sorted = sort{$a <=> $b} @data;
    print "Sorted numbers:\n";
    for ($x=0; $x<$size; $x++) 
    { 
    	print ("$sorted[$x]\n"); 
    } 
    
    #Printing the Largest Number
    print "The largest number is $sorted[$size-1]\n"
    
    #Printing the Smallest Number
    print "The largest number is $sorted[0]\n"

  2. #2
    Join Date
    Jun 2009
    Location
    Belgium (Country in Europe)
    Posts
    44

    Re: Perl - Finding the Smallest Number

    You forgot the ";" behind the last and second last print.


    Code:
    #Printing the Largest Number
    print "The largest number is $sorted[$size-1]\n";
    
    #Printing the Smallest Number
    print "The largest number is $sorted[0]\n";
    Greetz,
    Dave

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured