Divison by Zero Error

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pendragon
Forum Newbie
Posts: 18
Joined: Mon Mar 19, 2007 3:25 pm

Divison by Zero Error

Post by pendragon »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I'm getting a division by zero error when attempting to compute 
a semester GPA at the end of my code.  Must not be getting any values
from the function correctly.  Can anyone see the mistake?  Am new to 
passing values via functions.


Form:

Code: Select all

<html>
  <head>
    <title>Semester GPA Calculator</title>
    <style type='text/css'>
      th {text-align: left;}
    </style>
  </head>
  <body>
  <h2>Semester GPA Calculator</h2>
  <p>Please enter your course information:</p>
  <form action='script_semesterGPA.php' method='post'>
  <table width='50%'>
  <tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>
  <?php
  for ($i=0; $i<5; $i+=1) {
    print "<tr>\n";
    print "\t<td><input type='text' name='course$i'></td>\n";
    print "\t<td><input type='text' name='units$i' size=5></td>\n";
    print "\t<td><input type='text' name='letterGrade$i' size=5></td>\n";
    print "</tr>\n";
  }
  ?>
  </table>
  <input type='submit' value='Calculate GPA'>
  </form>
  </body>
</html>


Code: Select all

<?php

/** 
 *  This program consists of a form (form_semesterGPA.php) that allows the
 *  user to enter the classes they took during a semester.  Up to 5 course titles, 
 *  units, and final letter grades can be entered in the form.
 *  
 *  A separate PHP page (script_semesterGPA.php) will process the form.  This page
 *  calculates the student's GPA for the semester.
 *
 *  Steps to calculate the semester GPA:
 *     1.  Conversion of the letter grade entered for a course into a numeric
 *          equivalent with A = 4 points, B = 3 points, C = 2 points, D = 1 point,
 *          F = 0 points.
 *     2.  The point value of the letter grade is multipled by the number of units
 *          for the course to obtain a value called "quality points."
 *     3.  In order to get the GPA, the quality points for all courses are added up
 *           and then divided by the total number of units.
 *   
 *  The solution is to include a function called calculateQualityPoints which should
 *  take a letter grade and a number of units, and return the quality points for that
 *  course.
 *  
 *  The page should calculate GPA correctly irregardless of how many courses and info
 *  are entered.
 */
 
	
?>
<html> 
<head> 
<title>Get Your Semester GPA</title> 
</head> 
<body>
<table width="90%" border="1" cellpadding="0" cellspacing="5" > 
<?php 
// Set up array holder 
$form_info = array(); 

//  Get the array size
$size = count($form_info);
 
// Function calculateQualityPoints - takes a letter grade and a number of units &
//   returns the quality points for that course
	   function calculateQualityPoints($grades, $units)
	   {
         if($grades == "a" || $grades == "A"){ 
            $classPts = 4 * $units;
		    echo '<td><center>' . $classPts. '</center></td>';
			return $classPts; 
		 }
         if($grades == 'b' || $grades == 'B'){
            $classPts =  3 * $units;
			 echo '<td><center>' . $classPts. '</center></td>';
			 return $classPts;  
		 }
         if($grades == 'c' || $grades == 'C'){
		    $classPts =  2 * $units;
			 echo '<td><center>' . $classPts. '</center></td>'; 
			 return $classPts; 
		 }
         if($grades == 'd' || $grades == 'D'){
            $classPts =  1 * $units;
			 echo '<td><center>' . $classPts. '</center></td>'; 
			 return $classPts; 
		 }
         if($grades == 'f' || $grades == 'F'){
           $classPts =  0 * $units;
		     echo '<td><center>' . $classPts. '</center></td>'; 
			 return $classPts; 
         }
	   }
//  Check to see if data is submitted	   
if (!empty($_POST)) 
{
      for ($c = 0; $c < 5; $c++) 
      { 
        $form_info[$c]['course'] = $_POST['course' . $c] ; 
        $form_info[$c]['units'] = $_POST['units' . $c] ;
		$form_info[$c]['grade'] = $_POST['letterGrade' . $c] ; 
	  } 
    
       $count = count($form_info); 
       echo '<tr bgcolor=#FFCC99><th>Course</th><th>Units</th><th>Letter Grade</th><th>Quality Points</th></tr>';
	   
	  for ($i = 0; $i < $count; $i++)
	  { 
	    echo '<tr>'; 
        echo '<td><center>' . $form_info[$i]['course'] . '</center></td>'; 
        echo '<td><center>' . $form_info[$i]['units'] . '</center></td>';
		$units = $_POST['units' . $i] ; 
		
		echo '<td><center>' . $form_info[$i]['grade'] . '</center></td>'; 
		$grades = $_POST['letterGrade' . $i] ;
		$classPts = 0;
		calculateQualityPoints($grades,$units);
		$totalPts = 0;
		$totalPts += $classPts;
		$totalUnits = 0;
		$totalUnits += $units;
	  }
	    if ($totalUnits == 0){
		    $totalUnits = 1;
		     $totalGPA = @($totalPts/ $totalUnits);
			  print "<tr><td colspan='4'> Your total Semester GPA is  {$totalGPA} </td></tr>"; }
	    else 
		    {
			 $totalGPA = @($totalPts/ $totalUnits);
			 print "<tr><td colspan='4'> Your total Semester GPA is {$totalGPA} </td></tr>"; 
		}  
	    echo '</tr>';
	  
}
else
{   echo ( "<tr><td><h2>There is nothing to display</h2></td></tr>"); }


?>
</table> 
</body> 
</html>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Which line?

Something of note: you aren't storing the return from calculateQualityPoints() .. so $classPts will continue to be zero.

Also, setting variables to zero during each iteration of a loop will allow you to only track the last iteration afterward.
pendragon
Forum Newbie
Posts: 18
Joined: Mon Mar 19, 2007 3:25 pm

Storing the return value

Post by pendragon »

I thought that might be the problem - not getting the value passed from the function.

I'm new to this and not quite sure how to "store" the return value back in the main part of the program
so that the rest of the program can access it.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Here's an example of storing the return information from your own snippet:

Code: Select all

$size = count($form_info);
pendragon
Forum Newbie
Posts: 18
Joined: Mon Mar 19, 2007 3:25 pm

Getting the return value out of a function

Post by pendragon »

So.....

if I want to get the return value $classPts out of the function and back into the main program so I can use that value,

can I do something like placing the following line back in the main program?

$result = $classPts;
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Have you tried it?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

This could be the function:

Code: Select all

<?php
/** 
 * Calculates points for a given grade
 *
 * @access public
 * @param string $grades The letter grade used for the calculation
 * @param integer $units Te numeric unit value to multiply
 * @return integer Returns the numeric value of the units calculated from the grade
 */
function calculateQualityPoints($grades, $units)
{
    $classPts = 0;
    
    switch(strtolower($grades)) {
        case 'a':
            $classPts = 4 * $units;
            break;
        
        case 'b':
            $classPts = 3 * $units;
            break;
        
        case 'c':
            $classPts = 2 * $units;
            break;
        
        case 'd':
            $classPts = 2 * $units;
            break;
    }
    
    return $classPts;
}            
?>
This is a little lighter than your gaggle of if statements. You should validate inside the function, to make sure there is a grade and units passed, and to make sure they are of the appropriate type. But I'll leave that learning up to you. :wink:
Post Reply