简体   繁体   English

PHP除以零警告并带有检查

[英]PHP Division by zero warning with a check

I have a script that does some math and makes an excel sheet but i randomly get a 我有一个脚本,可以进行一些数学运算并制作一张Excel工作表,但我会随机获得一个

Warning: Division by zero in myfile.php on line 170

Which throws off my header() changes.. I say that its random because it will work one time but if i refresh the page it breaks the most confusing part is that i also have a check if its zero here is the code 我说它是随机的,因为它将工作一次,但是如果我刷新页面,它最令人困惑的部分是我还要检查其零值是否是代码

      167    if($cartonCount > 0){
      168     echo  "-----" . $cartonCount . "-----";
      169    $mellow = $qty/$cartonCount;
      170    $leftovers = $qty % $cartonCount;
      171    for($x = 1 ; $x <= $mellow ; $x++){

If the carton count is 0 it shouldn't run at all yet i still get the warning.. if anyone has an idea let me know here is a sample of the out put 如果纸箱计数为0,则根本不应该运行,但是我仍然会收到警告。如果有人有主意,请让我知道这是输出的样本

-2.38----------7.63----------12----------10----------7.5---------       
7.5----------4.5----------4.5----------4.5----------4.5----------7.5- 
---------1----------9.5----------7.5----------2.38----------0.06-----

Warning: Division by zero in /nfs/c08/h02/mnt/122022/domains/superstructs.com/html/catalog/test/samples/upsExport.php on line 170

-----2.38----------7.63----------7.5----------7.5----------2.38------
----0.06-----

Then, I'm putting this in as answer: 然后,我将其作为答案:

It might be because the value is NULL which, in fact, is not >0. 可能是因为该值是NULL,而实际上不是> 0。 But it will still give you that error 但是它仍然会给你那个错误

I notice that the place where it breaks is when $cartonCount is "0.06". 我注意到,当$ cartonCount为“ 0.06”时,它折断的地方。 I suspect that $cartonCount is being stored as a string, possibly with the European style 0,06 decimal notation. 我怀疑$ cartonCount是作为字符串存储的,可能是欧洲风格的0,06十进制表示法。 When PHP tries to convert that to a number, it sees it as a zero. 当PHP尝试将其转换为数字时,它将视为零。 I'm not sure why it is acting differently for the modulo operator and not for division or equality checks, but putting $cartonCount = intval($cartonCount) before line 167 should make things act consistently (although it might end up interpreting your 0.06 as a zero). 我不确定为什么它对模运算符而不是除法或相等性检查有不同的作用,但是将$cartonCount = intval($cartonCount)放在第167行之前应该会使情况一致(尽管最终可能会将您的0.06解释为零)。

The modulo operator converts (or rounds) the second number to an integer. 模运算符将第二个数字转换(或舍入)为整数。 0.06 results in 0 which creates the warning. 0.06的结果为0,这将创建警告。

Possible options are for example casting to integer or round() before checking > 0, round up using ceil() or check > 1. 可能的选项是例如在检查> 0之前强制转换为integer或round(),使用ceil()进行舍入或检查> 1。

Based on the context ceil() seems to be the best option. 根据上下文,ceil()似乎是最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM