dqftyn1717 2014-06-05 02:58
浏览 27
已采纳

交换机案例失败[重复]

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>
  • 写回答

2条回答 默认 最新

  • doudao2407 2014-06-05 03:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)