本文整理匯總了PHP中Calculator::calc方法的典型用法代碼示例。如果您正苦於以下問題:PHP Calculator::calc方法的具體用法?PHP Calculator::calc怎麽用?PHP Calculator::calc使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Calculator
的用法示例。
在下文中一共展示了Calculator::calc方法的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。
示例1: calc
break;
}
if ($need_push) {
array_push($this->stack, $r);
}
}
}
function calc($expression)
{
$this->stack = [];
$this->parser->parse($expression, [$this, '_calc']);
return $this->stack[0];
}
function tree($expression)
{
$this->parser->printTree($expression);
}
}
/////////////////////////////////////////////////////////////
if (realpath($_SERVER['SCRIPT_FILENAME']) == __FILE__) {
$calc = new Calculator();
while ($exp = fgets(STDIN)) {
try {
$result = $calc->calc($exp);
echo "{$result}\n";
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
}
exit;
}
示例2: testCalc
function testCalc()
{
$calc = new Calculator();
$result = $calc->calc('123');
$this->assertEquals(123, $result);
$result = $calc->calc('100 - (35 - 4)');
$this->assertEquals(100 - (35 - 4), $result);
$result = $calc->calc('2 * (3 + 4)');
$this->assertEquals(2 * (3 + 4), $result);
$result = $calc->calc('9 / 3 * 2');
$this->assertEquals(9 / 3 * 2, $result);
$result = $calc->calc('(4+1) * (6 - 1)');
$this->assertEquals((4 + 1) * (6 - 1), $result);
$result = $calc->calc('-(11+29)');
$this->assertEquals(-(11 + 29), $result);
$result = $calc->calc('4 - -3 * 4');
$this->assertEquals(4 - -3 * 4, $result);
$result = $calc->calc('-1 * -1');
$this->assertEquals(-1 * -1, $result);
$result = $calc->calc('2.5 * 8');
$this->assertEquals(2.5 * 8, $result);
$result = $calc->calc('cos pi/2');
$this->assertEquals(cos(M_PI) / 2, $result);
$result = $calc->calc('4 pi-1');
$this->assertEquals(4 * M_PI - 1, $result);
$result = $calc->calc('2cos -pi');
$this->assertEquals(2 * cos(-M_PI), $result);
}
示例3: switch
switch ($this->operator) {
case "+":
return $this->num1 + $this->num2;
break;
case "-":
return $this->num1 - $this->num2;
break;
case "*":
return $this->num1 * $this->num2;
break;
case "/":
if ($this->num2 == 0) {
echo "<script>alert('除數不能為0!');</script>";
return "除數不能為0!";
} else {
return $this->num1 / $this->num2;
}
break;
default:
break;
}
}
}
if (isset($_POST["btn"])) {
if (isset($_POST["op"])) {
$calculator1 = new Calculator($_POST["num1"], $_POST["num2"], $_POST["op"]);
echo "計算結果:" . $calculator1->calc();
} else {
echo "<script>alert('請選擇操作!');</script>";
}
}