Jump to content

Array Troubles


ijustdidit2011

Recommended Posts

Im trying to get the average of these scores for school could some one tell me what im doing wrong?

 

Thanks!

 

 

<?php

//mainline

 

$scores=array("6.7","8.1","5.8","7.0","6.6","6.0","7.6","6.1","7.2","7.0");

$judges=array("America","Germany","France","China","Japan","Russia","Chek Republic","Trinidad","Cuba","Jamaica");

$average=0;

 

 

doCalc($scores, $average);

//end mainline

 

    function doCalc($scores, $average)

{

  $scores[$average] = $scores[$average] / 10;

  $average = $scores[$average];

}

 

 

 

 

print("The scores are:  ");

for($i=0; $i<10; $i++)

{

print("\n\n{$judges[$i]}");

print("\n{$scores[$i]}");

 

}

print("\n\nThe Average score is $average");

?>

Link to comment
Share on other sites

You are not returning any values in your function, so the $scores and $average variables are terminated at the closing } of your function. To prevent this you could pass the parameters like this:

 

function doCalc( &$scores, &$average )

 

This is called passing variables by reference. It means that everything you do to those variables in your function, will stay that way, even when the function is closed.

Link to comment
Share on other sites

Try this mate.

 

<?php
//mainline

   $scores=array(6.7,8.1,5.8,7.0,6.6,6.0,7.6,6.1,7.2,7.0);
   $judges=array("America","Germany","France","China","Japan","Russia","Chek Republic","Trinidad","Cuba","Jamaica");
   $average=0;   
   
   
   $average=doCalc($scores, $average);
//end mainline
   
    function doCalc($scores, $average)
   {
      $total=0;
      foreach($scores as $score) {
        $total=$total + $score;
      }
      $result=($total / 10);
      return $average;
   }

   


print("The scores are:  ");
for($i=0; $i<10; $i++)
   {   
   print("\n\n{$judges[$i]}");
   print("\n{$scores[$i]}");
   
   }
   print("\n\nThe Average score is $average");
?>

 

Set it to loop through the array and add it all up and then return the average.

 

Regards

Liam

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.