dongqing904999 2016-09-13 03:58
浏览 71
已采纳

PHP数组值未被更改

I was trying to make a program to do synthetic division which requires factoring so I wrote this function to factor an integer which works, but it never changes the values of the php array $factors. Any help will be greatly appreciated.

$factors=array();
$i;
function factor($x){
    if($x==0){
        echo "(0,0)";
        } else {
            $n=false;
            if($x<0) {
                $x=abs($x);
                $n=true;
            }
            for($i=2; $i<=$x; $i++) {
                if($x%$i==0){
                    if($n){
                        $factors[(count($factors))]=(-1*($x/$i));
                        $factors[(count($factors))]=($i);
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=(-1*$i);
                    } else {
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=($i);
                    }
                }
            }
        }
    }
factor(-4);
  • 写回答

1条回答 默认 最新

  • dongwen1935 2016-09-13 04:05
    关注

    Try this

    function factor($x){
         $factors=array();
        if($x==0){
            echo "(0,0)";
        } else {
            $n=false;
            if($x<0) {
                $x=abs($x);
                $n=true;
            }
            for($i=2; $i<=$x; $i++) {
                if($x%$i==0){
                    if($n){
                        $factors[(count($factors))]=(-1*($x/$i));
                        $factors[(count($factors))]=($i);
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=(-1*$i);
                    } else {
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=($i);
                    }
                }
            } //end for
           echo '(' . implode(',', $factors). ')';
        } //end if $x == 0
    }
    factor(-4);
    

    $factors is outside the scope of the function, besides that you were not returning or outputting anything. Seeing as you echo (0,0) I assumed you wanted it echoed such as (2,4,8) etc. Which you can do with implode..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大