【问题标题】:How do I avoid division by zero error?如何避免除以零错误?
【发布时间】:2017-04-13 09:16:57
【问题描述】:

我有这样的代码:

 add_filter( 'woocommerce_sale_flash2', 'lx_custom_onsale_label', 10, 2 );
  function lx_custom_onsale_label() {
    global $product;

    $percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );
    $absolute = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) ) );

    if ($product->get_regular_price()  > 100) {
    return '<span class="onsalex bg_primary headerfont">'. sprintf( __(' -%s', 'salex' ), $absolute . ',-' ).'</span>';
    } 

    else if ($product->get_regular_price()  < 1) {
    return '<span class="onsalessszzzx bg_primary headerfont">'. sprintf( __(' -%s', 'salex' ), $absolute . ',-' ).'</span>';
    }   

    else {
    return '<span class="onsalexzzz bg_primary headerfont">'. sprintf( __(' -%s', 'salex' ), $percentage . '%' ).'</span>';
    }
}

一切正常,除了分隔符为 O 时,通知将显示:

警告:除以零 D:\SERVER\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\themes\MYTHEME\functions.php 在第 553 行

第 553 行是这段代码:

    $percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );

我不明白如何避免该代码上条件为零的警告。

非常感谢您的帮助。

【问题讨论】:

  • 厚脸皮的回答:不要除以零
  • 在操作前测试$product-&gt;get_regular_price()是否大于0
  • 如果您不想做某事,if 非常方便

标签: php wordpress


【解决方案1】:

替换:

$percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );

作者:

$percentage = 0;
if ( $product->get_regular_price() > 0 ) 
    $percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );

我知道奇怪的答案,但如果你不除以零,就没有错误。

解释

正如@domdom 指出的“不要除以零”,这是一个很好的答案,也是一种很好的做法,因为除以零在数学中是不“合法的”。

【讨论】:

  • 那么请使用upvote按钮下的复选标记来验证答案。谢谢
【解决方案2】:

只需检查$product-&gt;get_regular_price() 是否大于/不等于零(以防可能出现负值):

if ($product->get_regular_price() != 0){
  // Do stuff
} else {
  // Do something with the zero
}

只有正数:

if ($product->get_regular_price() > 0){
  // Do stuff
} else {
  // Do something with the zero
}

【讨论】:

  • 上面的答案是可行的,但我也试试你的代码。谢谢。
【解决方案3】:
if($product->get_regular_price()> 0)
{
//do your work
}

只检查除法前的价格是否为零。

【讨论】:

    【解决方案4】:

    替换这一行

     $percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );
    

     $percentage = $product->get_regular_price() != 0 ? round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 ) : 0;
    

    问题已经回答了,这只是使用三元运算符的另一种方法

    【讨论】:

      【解决方案5】:

      试试看。像这样的东西很简单但很有用..

      $var = @($val1 / $val2);
      

      【讨论】:

        猜你喜欢
        • 2010-10-26
        • 1970-01-01
        • 2019-12-18
        • 2014-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        • 1970-01-01
        相关资源
        最近更新 更多