我已经制作了一个PHP代码,用于将从数据库中检索的GPA转换为数字,如A,B,C等字母,等等,但即使GPA等于4.0,所有结果都是F. 这是我的代码告诉我,它有什么问题
while($row = mysqli_fetch_array($show_result))
{
//$data holds the array
$row['GPA'] = $grad;
if ($grad <= 0.9 && $grad >=0.0)
{
$grad = 'F';
}
else if ($grad<= 1.9 && $grad >=1.0 )
{
$grad = 'D';
}
else if ($grad <= 2.9 && $grad >=2.0)
{
$grad = 'C';
}
else if ($grad <= 3.9 && $grad >=3.0)
{
$grad = 'B';
}
else if ($grad == 4.0)
{
$grad = 'A';
}
echo "<td>" . $grad . "</td>";
答案 0 :(得分:3)
$row['GPA'] = $grad;
应为$grad=$row['GPA'];
答案 1 :(得分:0)
我知道你没有要求进行代码审查,但我不禁提出一些建议:
您确定成绩的逻辑不必与您的数据库代码或生成html的代码交织在一起。而且,如果截止值没有编入逻辑中,它将更加灵活和可维护。也许这样的事情开始:
/**
* Get a letter grade from a numeric GPA and a grading scale
* $scale is an array of letter grades keyed by minimum GPA cutoffs,
* and should be sorted in descending order by key (cutoff)
*/
function get_letter_grade ($numeric_grade, $scale)
{
$letter_grade = 'F';
foreach ($scale as $cutoff => $grade)
{
if ($numeric_grade >= $cutoff)
{
$letter_grade = $grade;
break;
}
}
return $letter_grade;
}
然后你可以像这样测试它(如果没有单元测试框架):
$scale = array (
4.0 => 'A',
3.0 => 'B',
2.0 => 'C',
1.0 => 'D',
);
$test = 0.0;
while ($test <= 4.0)
{
$grade = get_letter_grade ($test, $scale);
echo "letter grade for $test is $grade\n";
$test = round ($test + 0.1, 1); // round to avoid floating point error
}