Example #1
0
/**
 * Some tests to ensure that things are functioning as expected.
 * This should NOT be submitted.
 */
print "Beginning tests...\n";
$fail = $pass = 0;
$tests = array('2+2', '9*8', '144/12', '100-101', '10+-9', '.1+.25', '49', '2*3*-4', '3/2+1/3', '100-100/100', '-2/-3', '1/2+9/8*.5');
// Load the actual functions...
ob_start();
include 'calculator.php';
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');
Example #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>