php if elseif 语句问题
我正在为计算机科学课编写一个非常简单的 php 程序,但我在使用它时遇到了一些问题。
<?php
$numOfCards = '50'; //$_POST['numOfCards'];
$totalCost = 0.00;
if (numOfCards == '20')
{
$totalCost = $numOfCards*3.00;
}
else if (numOfCards == '50')
{
$totalCost = $numOfCards*2.50;
}
else
{
$totalCost = $numOfCards*2.00;
}
echo "<p>TOTAL COST FOR ".$numOfCards." CARDS: $".$totalCost."</p>";
?>
正如您所看到的,我最初是从发布数据中获取 $numOfCards 值,但将其设置为 50 以证明这一点。问题是这段代码本来应该转到 else if 语句,但它却转到 else 语句。这导致总成本等于 100 美元,而不是 125 美元。
有谁知道我做错了什么? 谢谢
I have a very simple php program that I am working on for my computer science class but I am having a little trouble with it.
<?php
$numOfCards = '50'; //$_POST['numOfCards'];
$totalCost = 0.00;
if (numOfCards == '20')
{
$totalCost = $numOfCards*3.00;
}
else if (numOfCards == '50')
{
$totalCost = $numOfCards*2.50;
}
else
{
$totalCost = $numOfCards*2.00;
}
echo "<p>TOTAL COST FOR ".$numOfCards." CARDS: $".$totalCost."</p>";
?>
As you can see, I was originally getting my $numOfCards value from post data but have set it to 50 to prove a point. The issue is that this code as it is should go to the else if statement but instead it is going to the else statement. This results in totalCosts equalling $100 instead of $125.
Does anyone know what I am doing wrong?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您似乎在
numOfCards
中两次缺少$
。为了更容易地发现这些问题,请在脚本顶部启用错误报告和警告:
然后您将看到两条消息,说明您不是与变量(如您想要的那样)进行比较,而是与字符串“numOfCards”进行比较>。
You seem to have a
$
missing innumOfCards
twice.To easier find these problems enable error reporting and warnings on top of your script:
Then you will see two messages explaining that instead of comparing against a variable (as you wanted to) you compared against the string
"numOfCards"
.您必须使用
$numOfCards
而不仅仅是numOfCards
。此外,您应该缩进您的代码块,最好每层有 4 个空格:
You have to use
$numOfCards
instead of justnumOfCards
.Additionally you should indent your code blocks, preferably with 4-spaces per level:
看起来您缺少变量名称中的
$
。http://ideone.com/Y89nu
It looks like you are missing the
$
in the variable names.http://ideone.com/Y89nu
是的,你错过了 $ 符号
代码应该是
Yes you missed a $ sign
The code should be