douchui4459 2011-04-30 14:12
浏览 158
已采纳

如何在Math类中创建减法方法?

I am studying OOP and this is my first study project.

I created a Math class and also created an add method. But when I am trying to create a subtract method I don't know where I am getting a problem.

Please kindly help and give me information where I can get more detailed information on OOP.

<?php

class Math
{
    /**
     *
     * @return int  
     */
    function add()
    {
        $args = func_num_args();
        $sum = 0;
        $i = 0;

        for ( $i; $i < $args; $i++ )
        {
            is_int(func_get_arg($i)) ? $sum += func_get_arg($i) : die('use only integers, please');
        }
        return $sum;
    }

    function subtract()
    {
        $args = func_num_args();
        $sub = 0;
        $i = 0;

        while($i < $args)
        {
            $sub = func_get_arg($i);
            if (is_int(func_get_arg($i)))
            {
                is_int($sub - func_get_arg($i));
            }    
        }
        $i++;
        return $sub;
    }
}

I am calling this class in my index.php like this:

<?php
    include("Math.php");

        $c = new Math();
        $result = $c->subtract(100,10,20,45);

        echo $result;
?>
  • 写回答

4条回答 默认 最新

  • dpy83214 2011-04-30 14:38
    关注

    There are a few small problems here:

    1. Your loop won't ever terminate because the incrementing of $i is outside of your while loop.
    2. The setting of $sub the first time should happen before the while loop. I assume your subtraction function is meant to subtract the latter arguments from the first argument. Right now, $sub is reset every pass through the loop.
    3. $sub's value is never updated by the subtraction operation in your loop. You need to assign a new value to $sub based on the subtraction. You can use the -= shorthand for this just like you used the += shorthand in your add() method.

    A working solution would look like this:

    $sub = func_get_arg( $i );         // At this point $i == 0
    
    while ( $i < $args ) {             // Loop while $i is less than the number of args
        $i++;                          // Increment $i
        $operand = func_get_arg( $i ); // Name the argument for clarity
    
        if ( is_int( $operand )) {     // Make sure the $operand is an integer
            $sub -= $operand;          // Update $sub by subtracting $operand from it
        } else {
            // Do some error handling here...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源