Case 语句输出不正确? [英] Case statement is not outputting correctly?
问题描述
这很奇怪,但以下是我的案例陈述:
This is very strange but below is my case statement:
switch($grade){
case ($average >70):
$grade = 'A';
break;
case ($average >=60 && $average <=69):
$grade = 'B';
break;
case ($average >=50 && $average <=59):
$grade = 'C';
break;
};
所以如果它的 70+ 是 A 级,60-69 B 级,50-59 C 级.
So if its 70+ it is grade A, 60-69 grade B, 50-59 grade C.
但它输出的是:60+ A级,50-59 B级,40-49 C级.
But instead it outputting this: 60+ grade A, 50-59 grade B, 40-49 grade C.
为什么要这样做,因为函数看起来是正确的?
Why is it doing this because function seems correct?
echo "<p><strong>Average Mark:</strong> $average</p>";
echo "<p><strong>Average Grade:</strong> $grade</p>";
推荐答案
正如其他人在评论中提到的,案例中的条件"应该是一个静态值,而不是一个逻辑表达式.
As others mentioned in comments, the "condition" in a case should be a static value, not a logical expression.
此外,您打开的值(在您的情况下,$grade
)应该是您正在测试的值.您似乎在使用它作为关于您正在分配的变量的提示.
Also, the value you're switching on (in your case, $grade
) should is the one you're testing. You appear to be using it as a hint about what variable you're assigning.
修复代码的最简单方法是使用 if-elseif-else 结构:
The simplest way to fix your code would be to use an if-elseif-else construct:
if ($average >70)
$grade = 'A';
elseif ($average >=60 && $average <=69)
$grade = 'B';
elseif ($average >=50 && $average <=59)
$grade = 'C';
然而,为了说明 switch 语句的工作原理,您还可以执行以下操作:
However, to be perverse, and to illustrate how a switch statement works, you could also do the following:
switch(true){
case ($average >70):
$grade = 'A';
break;
case ($average >=60 && $average <=69):
$grade = 'B';
break;
case ($average >=50 && $average <=59):
$grade = 'C';
break;
};
在这个例子中,我将值 true
依次与每个 case 进行比较,其中每个 case-values 实际上是评估布尔表达式的结果.值与 true
匹配的第一个表达式将触发.
In this example I'm comparing the value true
to each of the cases in turn, where each of those case-values is actually the result of evaluating a boolean expression. The first expression whose value matches true
will fire.
如果您不了解 switch 语句,可能没有太大帮助.
Probably not much help, if you don't understand switch statements.
编辑:我刚刚注意到逻辑上有一个差距:如果某人的平均分正好是 70 呢?使用像 switch 或 if-else 这样的级联语句,您可以消除一些冗余(在这种情况下是破坏性的)代码,因此:
Edit: I just noticed that there's a gap in the logic: what if someone's average is exactly 70? Using a cascading statement like a switch or if-else, you can eliminate some of the redundant (and in this case damaging) code, thus:
if ($average >=70)
$grade = 'A';
elseif ($average >=60)
$grade = 'B';
elseif ($average >=50)
$grade = 'C';
// ...
else
$grade = 'F';
...依此类推,直到您使用的最低等级.
...and so on, to whatever lowest grade you're using.
这篇关于Case 语句输出不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!