我被困在解決PHP腳本。php計算器類
我想計算一組指令的結果。說明由每行空格分隔的關鍵字和數字組成。指令從文件加載並將結果輸出到屏幕。可以指定任意數量的指令。指令是操作符(添加,除,減,乘)。說明將忽略數學優先級。最後一條指令應該是「apply」和一個數字(例如「apply 3」)。計算器隨後用該號碼初始化,並將前面的指令應用於該號碼。
[Input]
add 2
multiply 3
apply 3
[Output]
15
這是我已經試過,但我不能讓邏輯來完成方法
class Calculator {
public $result = 0;
public $queue = Array();
public parseString($text) {
// parse input string
$cmds = explode(" ", $text);
foreach($cmds as $cmd) {
$cmd = trim($cmd);
if(!$cmd) continue; // blank or space, ignoring
$this->queue[] = $cmd;
}
// lets process commands
$command = false;
foreach($this->queue as $index => $cmd) {
if(is_number($cmd)) {
// if it's number fire previous command if exists
if(!$command || !method_exists($this, $command)) {
throw new Exception("Unknown command $command");
}
$this->$command($index, $cmd);
}else{
$command = $cmd;
}
}
}
public function apply($index, $number) {
// manipulate $result, $queue, $number
}
public function add($index, $number) {
// manipulate $result, $queue, $number
}
public function substract($index, $number) {
// manipulate $result, $queue, $number
}
}
$calculator = new Calculator();
$calculator->parseString('...');
我怎麼能叫或切換加,除,乘。減去和如何區分和觸發申請word
任何形式的幫助將不勝感激。
thnks JHON,我遍歷併成立了怎麼能先申請,對不起PHP的水平,我有。 –
生病編輯我的答案,包括那一刻。 – Tristan
感謝JHON我抄的代碼,因爲它是,它被賦予了錯誤的輸出,僅取第一個數字,而不是做加法的任何操作或乘或任何 –