PHP 减法

发布于 2024-12-26 17:45:24 字数 132 浏览 8 评论 0原文

我必须从另一个数字中减去一个数字,但脚本必须验证这是否可以在不给出负数的情况下进行。

例如,客户的信用额为 5.00 美元。他们想要购买 20 美元,但现在还缺 15 美元,因此无法购买。现在它必须将它们重定向到一个页面(资金不足)。

I have to subtract a number from another number, but the script must verify that this is possible without giving a negative number.

For example, the client's credit is $5.00. They want to make a purchase of $20, now they are short by $15 so they cannot make the purchase. Now it must redirect them to a page (Insuffient funds).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

往日 2025-01-02 17:45:24
$toBill = 20.0;
$myMoney = 5.0;

if( $myMoney >= $toBill )
{
  // process
  $myMoney -= $toBill;
}
else
{
  // error
  header('Location: /error_nsf/');
  exit;
}

编辑:这个问题表明您还没有充分了解基础知识。你应该去阅读有关流程结构和条件等的内容,如果你这样做的话,这样的事情会变得容易得多。

$toBill = 20.0;
$myMoney = 5.0;

if( $myMoney >= $toBill )
{
  // process
  $myMoney -= $toBill;
}
else
{
  // error
  header('Location: /error_nsf/');
  exit;
}

EDIT: This question screams that you've not sufficiently learned the basics. You should go read about flow constructs and conditionals and such, things like this will become much much easier if you do.

橘亓 2025-01-02 17:45:24

这是一个基本条件,

$balance = 5.00;
$debit   = 20.00;
if ($debit > $balance) {
    // handle the error
} else {
    $balance -= $debit;
}

This is a basic conditional,

$balance = 5.00;
$debit   = 20.00;
if ($debit > $balance) {
    // handle the error
} else {
    $balance -= $debit;
}
游魂 2025-01-02 17:45:24
$toBill = 20.0;
$myMoney = 5.0;

$myMoney = $toBill <= $myMoney ? $myMoney - $toBill : header('Location: insuficcientFunds.php');
$toBill = 20.0;
$myMoney = 5.0;

$myMoney = $toBill <= $myMoney ? $myMoney - $toBill : header('Location: insuficcientFunds.php');
明媚殇 2025-01-02 17:45:24

另一个解决方案是使用一个函数来检查购买是否有效(关于信用值),如下所示:

function purchaseIsValid( $purchaseValue, $creditValue )
{
    return ($purchaseValue <= $creditValue ); // returns true or false
}

然后在您的主应用程序中执行每个人建议的操作:

$purchase = 20.0;
$credit = 5.0;
if( purchaseIsValid( $purchase, $credit ))
{
    // process
}
else
{
    // error
}

祝您有美好的一天!

Another solution would be to use a function that checks if a purchase is valid, in regards to the credit value, like so:

function purchaseIsValid( $purchaseValue, $creditValue )
{
    return ($purchaseValue <= $creditValue ); // returns true or false
}

And then in you main application do something like everyone suggested:

$purchase = 20.0;
$credit = 5.0;
if( purchaseIsValid( $purchase, $credit ))
{
    // process
}
else
{
    // error
}

Have a great day!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文