你能帮我解释一下这段代码吗?

时间:2017-04-19 09:06:49

标签: php while-loop

<?php

$val = 999;
$sum = 0;
while($val){
   $sum += $val % 10; 
   $val = $val / 10; 
} 
echo $sum;

?>

请帮我解释一下上面的代码, 为什么$ sum是$ val的所有数字的总和?

3 个答案:

答案 0 :(得分:3)

所以你的代码是;

<?php

  $val = 999;
  $sum = 0;
  while($val){
     $sum += $val % 10; 
     $val = $val / 10; 
  } 
  echo $sum;
?>

现在进入while循环;

                           Iteration 1     Iteration 2      Iteration 3
 while($val){           |while(999){    |while(99){     |while(9){
     $sum += $val % 10; |$sum +=999%10; |$sum +=99%10;  | $sum+=9%10;
     $val = $val / 10;  |$val=999/10;   |$val=99/10;    | $val=9/10;
  }                     |}              |}              |}
                        |$sum=9;        |$sum=9+9=18    |$sum=18+9=27
                        | $val=99       |  $val=9       |$val=0

现在$ val是0;所以循环将退出;

echo $sum

将打印27

答案 1 :(得分:0)

%是余数。

所以你循环遍历$ val,这不是一个数组,因此它将循环为999和99和9。 因此,$ sum将剩余的9%10加起来,每次为9。

因此,对于每个数字(9 9 9),余数为9.所以你的结果是27。

代码$val / 10是实际的分频器,它使每个循环的数字999偏移10,因此第一个循环999/10 = 99,第二个循环99/10 = 9,第三个循环结果为0。这就是$ val的值数量下降所以循环结束。

答案 2 :(得分:0)

@Wawan Sumardi尝试了解下面的执行步骤:

<?php
$val = 999;
$sum = 0;
  

第1步

 while($val){ //$val = 999, while condition is true
   $sum += $val % 10; //$sum = 9 as % operator give you the remainder
   $val = $val / 10; //this / only for removing digit one by one to your $val means the current digit has been added in $sum now we don't have to add current digit again so your $val will be like 999, 99, 9, 0 this only because you want sum all the digits so it is needed this is the logic
}
  

第2步

while($val){ //now $val = 99, again while condition is true
   $sum += $val % 10; //again get 9 but the previous $sum = 9 so with += increment operator it will be added in $sum so now $sum = 18
   $val = $val / 10; //previous $val = 99 now $val = 9
}
  

第3步

while($val){ // now $val = 9, again while condition is true
   $sum += $val % 10; //again 9 but the previous $sum = 18 so with += increment operator it will be added in $sum so now $sum = 27
   $val = $val / 10; //previous $val = 9 now $val = 0
}
  

第4步

while($val){ // now as $val = 0, 0 is false value so now while condition is false so it break the while loop and below you will get $sum = 27
   $sum += $val % 10;
   $val = $val / 10;
}

echo $sum;
  

输出:27