2017-05-11 57 views
0

我有可能很愚蠢的問題,但我有這樣的代碼:PHP - 加減

<?php 
$x=2; 
$y=4; 
print ("iloczyn = ".$x." * ".$y." = ".$x*$y. "<br>"); 
print ("iloraz = ".$x."/".$y." = ".$x/$y. "<br>"); 
print ("suma = ".$x." + ".$y." = ".$x+$y. "<br>"); 
print ("roznica = ".$x." - ".$y." = ".$x-$y. "<br>"); 
?> 

而且它不工作。前兩個,乘法和除法都很好。但加減法不好。 該腳本的結果是這樣的:

iloczyn = 2 * 4 = 8 
iloraz = 2/4 = 0.5 
4 
-4 

任何想法爲什麼? 在此先感謝!

+3

運算符優先。 –

+2

與其他操作一起使用串聯時,始終使用括號。 – imtheman

回答

1

括號拯救生命:

$x=2; 
$y=4; 
print ("iloczyn = ".$x." * ".$y." = ".($x*$y). "<br>"); 
print ("iloraz = ".$x."/".$y." = ".($x/$y). "<br>"); 
print ("suma = ".$x." + ".$y." = ".($x+$y). "<br>"); 
print ("roznica = ".$x." - ".$y." = ".($x-$y). "<br>"); 
+1

太簡單了...謝謝! :) – sunrise

+0

2分鐘之內擊敗我! – pendo

0

你串聯,所以它們轉換爲字符串。把parens放在身邊,它會正常工作。

$x= 2; 
$y= 4; 
print ("iloczyn = ".$x." * ".$y." = ".($x*$y). "<br>"); 
print ("iloraz = ".$x."/".$y." = ".($x/$y). "<br>"); 
print ("suma = ".$x." + ".$y." = ".($x+$y). "<br>"); 
print ("roznica = ".$x." - ".$y." = ".($x-$y). "<br>");