交换机案例失败[重复]

This question already has an answer here:

I have a function like this:

public static function GetNilaiHuruf($nilai)
{
  if($nilai > 4)
  {
    $nilai = (float) ((float)($nilai) / (float)(100.0) * (float)4.0);
  }

  switch($nilai)
  {
    case ($nilai > 3.66 && $nilai <= 4) :
      return "A";
      break;
    case ($nilai > 3.33 && $nilai <= 3.66) :
      return "A-";
      break;
    case ($nilai > 3.00 && $nilai <= 3.33) :
      return 'B+';
      break;
    case ($nilai > 2.66 && $nilai <= 3.00) :
      return 'B';
      break;
    case ($nilai > 2.33 && $nilai <= 2.66) :
      return 'B-';
      break;
    case ($nilai > 2.00 && $nilai <= 2.33) :
      return 'C+';
      break;
    case ($nilai > 1.66 && $nilai <= 2.00) :
      return 'C';
      break;
    case ($nilai > 1.33 && $nilai <= 1.66) :
      return 'C-';
      break;
    case ($nilai > 1.00 && $nilai <= 1.33) :
      return 'D+';
      break;
    case ($nilai >= 0.00 && $nilai <= 1.00) :
      return 'D';
      break;
  }
}

When I call that function with $nilai is 0, the function returns 'A'; When I call that function with $nilai is 0.007 or 'x', the function returns 'D'.

How is that possible?

</div>

That is not how switch statements work, they shouldn't be used to do numeric comparisons like that.

However, you can achieve what you want by using boolean true as your switch argument:

$yourvar = -20;

switch(true) {
    case ($yourvar > 0 && $yourvar < 5) :
        echo 'Hello world!';
        break;
    case ($yourvar < 0) : 
        echo 'Hello hell!';
        break;
}

// Hello hell!

Please see this article for more info.

There's no need to try to use a switch here. Use if/else if/else:

if ($nilai > 3.66 && $nilai <= 4) {
    return "A";
} else if ($nilai > 3.33 && $nilai <= 3.66) {
    return "A-";
} ...