dongqing904999
dongqing904999
2016-09-13 03:58

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 dongwen1935 5年前

    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..

    点赞 评论 复制链接分享