예제 #1
0
ob_end_clean();
foreach ($tests as $test) {
    eval('$expect = ' . $test . ';');
    print "Testing {$test} = {$expect} ... ";
    $result = evaluate_postfix_expression(infix_to_postfix($test));
    if (!is_valid_expression($test)) {
        $fail++;
        print "Marked as invalid expression - FAIL\n";
    } else {
        if ($result == $expect) {
            $pass++;
            print "Passed!\n";
        } else {
            print "Got {$result} - FAIL\n";
            $fail++;
        }
    }
}
// Now, make sure desired failures fail
$failures = array('one/zero', '1+3+', '+3+7', '1.04.2 + 7', '.+17', '1**3', '1*/3', '1*+3', '1/*3', '1//3', '1/+3', '1+*3', '1+/3', '1++3', '1-*3', '1-/3', '1-+3');
foreach ($failures as $failure) {
    print "Testing {$failure} ... ";
    if (!is_valid_expression($failure)) {
        $pass++;
        print "Detected as invalid. Passed!\n";
    } else {
        $fail++;
        print "Detected as valid. FAIL\n";
    }
}
print "Tests complete! {$fail} failures | {$pass} successes\n";
예제 #2
0
	<input type="submit" value="Calculate">
</form>
<p>Some rules:
	<ul>
		<li>Expressions will be computed following the order of operations.</li>
		<li>Only the following operators are supported: *, +, -, /. Parenthesis are not supported.</li>
		<li>You may enter whole numbers (e.g. 1) or decimal (floating point) numbers (e.g. 1.2).</li>
		<li>Negative numbers are acceptable.</li>
		<li>Non-numeric characters, other than the operators above, are not allowed.</li>
		<li>Spaces will be ignored.</li>
	</ul>
</p>
<?php 
/**
 * Compute the result, if an expression is provided. If there's an error,
 * simply display it.
 */
if ('' != $expression) {
    echo '<h2>Results</h2>';
    if (!is_valid_expression($expression)) {
        echo "Invalid input expression {$expression}.";
    } else {
        echo "{$expression} = " . evaluate_postfix_expression(infix_to_postfix($expression));
    }
}
/** 
 * Finish up the "template"
 */
?>
	</body>
</html>