2015-05-13 29 views
-1

我正在讀取文本文件中的數據並執行一些基本的數學運算。這是事情應該如何工作:除數爲「0.0」時通過零警告的劃分

// no warning, expected result N/A 
$dividend = 100; 
$divisor = 0.0; 
if (!empty($dividend) && !empty($divisor)) 
{ 
    $quotient = $dividend/$divisor; 
} else { 
    $quotient = 'N/A'; 
} 
echo $quotient; 

這是事情是如何發生的。

// yeilds division by zero warning 
$dividend = 100; 
$divisor = '0.0'; 
if (!empty($dividend) && !empty($divisor)) 
{ 
    $quotient = $dividend/$divisor; 
} else { 
    $quotient = 'N/A'; 
} 
echo $quotient; 

我被零警告時,在文本文件中的值被讀作「0.0」,這empty()認爲非空,當它實際上空得到一個師。

什麼是測試'0.0'實際上是0的最好方法?

+0

使用http://php.net/manual/en/function.floatval.php – naththedeveloper

回答

1

您將要在您的條件語句中進行強制轉換(或使用floatval())。這使得你的價值不變的情況下,您需要輸入變量的其他數據,如結尾文本:

$dividend = 100; 
$divisor = '0.0'; 
if ((float)$dividend && (float)$divisor) //both are non-zero 
{ 
    $quotient = $dividend/$divisor; 
} else { //one or the other are zero 
    $quotient = 'N/A'; 
} 
echo $quotient; 

但是考慮只檢查$divisor爲零。

3

類型轉換$divisor浮動:$divisor = (float)'0.0';

+0

不應該是'(雙)'?而不是'(浮動)'?編輯:都似乎工作,沒關係。 – naththedeveloper

+0

@ɴᴀᴛʜ這取決於他需要小數點後的數字。 Float - 32位(7位),Double - 64位(15-16位) – Daan

+0

@Daan在PHP中,'(double)'和'(real)'都是'(float)'的別名。 PHP只有一個浮點類型。 – deceze

0

角色它爲int;

$divisor = (int) '0.0'; 
+4

爲什麼int?如果'$ divisor'是0.4,會發生什麼? – Daan

+0

當然,它可能是,但它也可能是「蘑菇」。事實是,我們不知道最初是什麼導致'$ divisor'成爲'「0.0」'。也沒有具體要求。 – psycotik

0

如果divisior爲零,我認爲商應該爲零。 因此,您在下列操作中獲得結果,而不是N/A。

我總是解決這個問題是這樣的:

$quotient = ($divisor == 0) ? 0 : ($divident/$divisor); 

應該爲"0.0"工作,太。