繁体   English   中英

使用 oops 概念制作一个 php 计算器类

[英]Make a php calculator class using oops concepts

嗨,伙计们,我正在尝试制作一个 php 计算器类,它需要通过功能生成多个数字,就像当用户尝试通过命令行 claculator.php 添加 2,3,4,5,6 时这样运行时,它应该给出输出为 20 和它应该允许 add 方法使用换行符 \\n 作为数字分隔符示例计算器.php add 2\\n 3,4

它应该允许定义用于分隔数字的分隔符示例:calculator.php add \\\\;\\\\2;3;4

它也不应该接受负数。如果用户传递的数字超过 1000,它应该忽略并给我结果,例如 phpcalculator.php add 10,20,1010,20 并且它应该 ginore 1010 并给出 50

我已经尝试过这个只接受 2 个参数的代码

 class Calculator {
    private $_val1 , $_val2;

    public function __construct($val1, $val2){
        $this->_val1 = $val1;
        $this->_val2 = $val2;
    }

    public function add(){
        return $this->_val1 + $this->_val2;
    }

    public function subtract(){
        return $this->_val1 - $this->_val2;
    }

    public function multiply (){
        return $this->_val1 * $this->_val2;
    }

    public function divide () {
        return $this->_val1 / $this->_val2;
    }
}

$calc = new Calculator(3,4);
echo "<p>3 + 4 = ".$calc->add(). "</p>";

$calc = new Calculator (15,12);
echo "<p>15 - 12 = ".$calc->subtract(). "</p>";

$calc = new Calculator (20,2);
echo "<p> 20 * 2 = ".$calc->multiply(). "</p>";

$calc = new Calculator (20,2);
echo "<p> 20 / 2 = ".$calc ->divide(). "</p>";

任何人都可以帮助我如何做这些事情

提前致谢。

我想这就是你要找的:

计算器类

<?php

/**
 * Calculator class
 */
class Calculator
{
    const min = 0;
    const max = 1000;

    /**
     * Calculate the summation
     * @param Array $number
     * @return integer
     */
    public static function add( $numbers ){
        return array_sum( self::_filter_numbers( $numbers ) );
    }

    /**
     * Substract numbers
     * @param Array $numbers
     * @return integer
     */
    public static function subtract( $numbers ){
        $filtered_numbers = self::_filter_numbers( $numbers );
        $first_number = array_shift( $filtered_numbers );
        return ( $first_number - array_sum( $filtered_numbers ) );
    }

    /**
     * Calculate the product of the given numbers
     * @param Array $numbers
     * @return integer
     */
    public static function multiply( $numbers ){
        return array_product( self::_filter_numbers( $numbers ) );
    }


    /**
     * Divide the given numbers
     * @param Array $numbers
     * @return double
     */
    public static function divide( $numbers ){
        $filtered_numbers = self::_filter_numbers( $numbers );
        $first_number = array_shift( $filtered_numbers );
        return ($first_number / array_product( $filtered_numbers ));
    }


    /**
     * Filter Invalid numbers
     * @param Array $numbers
     * @return Array Valid Numbers
     */
    private static function _filter_numbers( $numbers ){
        return array_filter( $numbers, function( $number ){
            return self::_is_valid_number( $number );
        } );
    }

    /**
     * Check if the given number is in the interval [0, 1000]
     * @param integer $number
     * @return boolean
     */
    private static function _is_valid_number( $number ){
        return ( $number >= self::min && $number <= self::max );
    }
}

测试

$test_numbers_1 = [ -2, -1, 0, 1, 2, 1000, 2000 ];
printf( "<h4>Test 1</h4>\n" );
printf( "<p>Numbers: %s</p>\n", implode( ',', $test_numbers_1 ) );
printf( "<p>Add: %d</p>\n", Calculator::add( $test_numbers_1 ) );
printf( "<p>Substract: %d</p>\n", Calculator::subtract( $test_numbers_1 ) );
printf( "<p>Multiply: %d</p>\n", Calculator::multiply( $test_numbers_1 ) );
printf( "<p>Divide: %f</p>\n", Calculator::divide( $test_numbers_1 ) );

$test_numbers_1 = [ -2, -1, 1, 2, 1000, 2000 ];
printf( "<h4>Test 2</h4>\n" );
printf( "<p>Numbers: %s</p>\n", implode( ',', $test_numbers_1 ) );
printf( "<p>Add: %d</p>\n", Calculator::add( $test_numbers_1 ) );
printf( "<p>Substract: %d</p>\n", Calculator::subtract( $test_numbers_1 ) );
printf( "<p>Multiply: %d</p>\n", Calculator::multiply( $test_numbers_1 ) );
printf( "<p>Divide: %f</p>\n", Calculator::divide( $test_numbers_1 ) );

检测结果

<h4>Test 1</h4>
<p>Numbers: -2,-1,0,1,2,1000,2000</p>
<p>Add: 1003</p>
<p>Substract: -1003</p>
<p>Multiply: 0</p>
<p>Divide: 0.000000</p>
<h4>Test 2</h4>
<p>Numbers: -2,-1,1,2,1000,2000</p>
<p>Add: 1003</p>
<p>Substract: -1001</p>
<p>Multiply: 2000</p>
<p>Divide: 0.000500</p>
<?php

$opt = getopt('s:n:m:');

try{
    if(!array_key_exists('n', $opt)){
        throw new InvalidArgumentException('Missing parameter "n"');
    }

    if(!array_key_exists('m', $opt)){
        throw new InvalidArgumentException('Missing parameter "m"');
    }

    if(array_key_exists('s', $opt)){
        $calc = new Calculator($opt['n'], $opt['m'], $opt['s']);
    }else{
        $calc = new Calculator($opt['n'], $opt['m']);
    }

    echo $calc;
}catch(Exception $exception){
    echo $exception->getMessage();
}

/**
 * Class Calculator
 */
class Calculator{

    /**
     * Min allowed value
     */
    const MIN = 0;
    /**
     * Max allowed value
     */
    const MAX = 1000;

    /**
     * Operators
     */
    const OPERATORS = ['add'      => '+',
                       'subtract' => '-',
                       'multiply' => '*',
                       'divide'   => '/'];

    /**
     * Separator
     * @var string
     */
    private $separator = ' ';
    /** @var array */
    private $numbers = [];
    /** @var string */
    private $method;

    /**
     * Calculator constructor.
     *
     * @param string $numbers
     * @param string $method
     * @param string $separator
     */
    public function __construct(string $numbers, string $method, string $separator = ' '){
        $this->separator = $separator;
        $this->method    = $method;
        $this->numbers   = $this->parseNumbers($numbers);
    }

    /**
     * @return mixed
     */
    public function calculate(){
        return $this->{$this->method}();
    }

    /**
     * @return float
     */
    public function add(): float{
        return (float)array_sum($this->numbers);
    }

    /**
     * @return float
     */
    public function subtract(): float{
        $numbers = $this->numbers;
        $result  = array_shift($numbers);
        foreach($numbers as $number){
            $result -= $number;
        }

        return (float)$result;
    }

    /**
     * @return float
     */
    public function multiply(): float{
        return (float)array_product($this->numbers);
    }

    /**
     * @return float
     * @throws Exception
     */
    public function divide(): float{
        $numbers = $this->numbers;
        $result  = array_shift($numbers);
        foreach($numbers as $number){
            if($number == 0){
                throw new Exception('Div by zero.');
            }
            $result = $result / $number;
        }

        return (float)$result;
    }

    /**
     * @param string $numbers
     *
     * @return array
     */
    private function parseNumbers(string $numbers): array{
        $numbers = explode($this->separator, $numbers);
        $numbers = $this->checkNumbers($numbers);
        $numbers = array_map(function($value){
            $value = trim($value);
            if(is_numeric($value)){
                return (float)$value;
            }
        },
            $numbers);
        $numbers = array_filter($numbers,
            function($value){
                return ($value !== null);
            });

        return (array)$numbers;
    }

    /**
     * @param array $numbers
     *
     * @return array
     */
    private function checkNumbers(array $numbers): array{
        return array_filter($numbers,
            function($value){
                if($value < 0){
                    throw new Exception('Negative numbers not allowed');
                }

                return ($value >= self::MIN AND $value <= self::MAX);
            });
    }

    /**
     * @return string
     */
    public function __toString(): string{
        try{
            $numbers = $this->numbers;
            $output  = array_shift($numbers);
            foreach($numbers as $number){
                $output .= ' '.self::OPERATORS[$this->method].' '.$number;
            }
            $output .= ' = '.$this->calculate();

            return trim($output);
        }catch(Exception $exception){
            return $exception->getMessage();
        }
    }
}

用法

php index.php -m add -n "1 2 3 4 5" // print 1 + 2 + 3 + 4 + 5 = 15
php index.php -m subtract -n "1 2 3 4 5" // print 1 - 2 - 3 - 4 - 5 = -13
php index.php -m multiply -n "1 2 3 4 5" // print 1 * 2 * 3 * 4 * 5 = 120
php index.php -m divide -n "1 2 3 4 5" // print 1 / 2 / 3 / 4 / 5 = 0.0083333333333333

php index.php -m add -s ";" -n "1;2;3;4;5" // print 1 + 2 + 3 + 4 + 5 = 15
php index.php -m add -n "1 2 3 4 5 2000" // print 1 + 2 + 3 + 4 + 5 = 15
php index.php -m divide -n "0 1 2 3 4 5" // print 0 / 1 / 2 / 3 / 4 / 5 = 0
php index.php -m add -n "1 2 3 4 5 -20" // print Negative numbers not allowed
php index.php -m divide -n "1 0 2 3 4 5" // print Div by zero.

php index.php -m add -n "1
2 3 4 5" // print 1 + 2 + 3 + 4 + 5 = 15

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM