Write a script that allows a user to enter a numeric grade and then determine th
ID: 3820312 • Letter: W
Question
Write a script that allows a user to enter a numeric grade and then determine the letter grade. Use a PHP document and a HTML document containing a form with 5 text boxes to enter the numeric grades. Print a message to the user stating whether or not the grade is valid (remember the numeric grade can only be between 0 – 100), and the letter grade for each numeric grade entered. Use the grade determination criteria from the syllabus. Example if a grade between 90 – 93 is entered, a letter of A- will display to the screen. If only 4 grades were entered, then only 4 letter grades should be listed to the screen. Save the documents as grades.html and grades.php.
Explanation / Answer
grades.php:
<?php
$num_boxes = 5;
$precision = 1;
$gradetext = '';
//minimum=>grade
$grade_array = array(
'97'=>'A+',
'94'=>'A',
'90'=>'A-',
'87'=>'B+',
'84'=>'B',
'80'=>'B-',
'77'=>'C+',
'74'=>'C',
'70'=>'C-',
'67'=>'D+',
'65'=>'D',
'0'=>'F'
);
function create_form($num_boxes=1)
{
if(is_int($num_boxes))
{
$form = '';
for($i=0;$i<$num_boxes;$i++)
{
$inc = $i+1;
$val = (isset($_POST['grade'][$i])) ? $_POST['grade'][$i] : '';
$form .= "<label for='grade$inc'>Grade $inc:</label><input id='grade$inc' name='grade[$i]' type='number' value = '$val' min='0' max='100' />";
}
return $form;
}
}
function get_grade($pc,$grade_array)
{
foreach($grade_array as $min=>$grade)
{
if($pc < $min) continue;
return $grade;
}
}
if($_POST)
{
$GPA = 0;
$num_posts = count(array_filter($_POST['grade'], "is_numeric"));
$total = array_sum($_POST['grade']);
if($num_posts != 0) $GPA = $total/$num_posts;
$lettergrade = get_grade($GPA,$grade_array);
$gradetext = "The GPA = " . number_format($GPA,$precision) . " ($lettergrade)";
}
?>
grades.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo $gradetext;?>
<form method="post">
<?php echo create_form($num_boxes);?>
<input type="submit" value="Calculate" />
</form>
</body>
</html>
-----Please rate my answer if you like it!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.