1

我制作了一个 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>";
4

2 回答 2

3

$row['GPA'] = $grad;应该$grad=$row['GPA'];

于 2013-06-15T18:28:49.493 回答
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
}
于 2013-06-15T18:51:20.967 回答