我必须计算可被5整除的数字。
这是我的代码,
$num = array(4, 25, 60, 7, 8);
foreach ($num as $numbers) {
if (($numbers % 5) == 0) {
echo count($numbers);
}
}
上述程序的输出为11.但输出应为2.请给我解决方案。提前谢谢。
答案 0 :(得分:1)
你也可以这样使用,
function divisibleby5($var){
return $var % 5 == 0;
}
$num = array(4, 25, 60, 7, 8);
echo count(array_filter($num,'divisibleby5');
答案 1 :(得分:1)
$nums = array(4, 25, 60, 7, 8);
仅计算:
- 基本:
$count = 0;
foreach ($nums as $num) {
if ( $num % 5 == 0 ) $count++;
}
- 使用类型进行播放:
$count = 0;
foreach ($nums as $num) {
$count += !($num % 5);
}
$num % 5
返回一个整数,!($num % 5)
返回一个布尔值,但因为它被用作+
运算符的操作数,false
和{{ 1}}表现得像true
和0
。
- 使用1
的功能版:
array_reduce
要过滤商品,请使用名为$count = array_reduce($nums, function($c, $i) { return $c + !($i % 5); });
的商品:
array_filter
并根据需要计算之后的项目数:
$result = array_filter($nums, function ($i) { return $i % 5 == 0; });
答案 2 :(得分:0)
我认为你需要做更多类似的事情。
$num = array(4, 25, 60, 7, 8);
$numbers=array();
foreach( $num as $number ) {
if( $number % 5 == 0 ) $numbers[]=$number;
}
echo count( $numbers );
或者使用array_walk
和自定义回调函数
function mod5($item,$key,$arr){
if($item %5==0)$arr[]=$item;
}
array_walk( $num,'mod5',&$numbers);
echo count($numbers);
答案 3 :(得分:0)
此处输出为1和1.不是11(十一) 你可以尝试一下
echo count($numbers)."<br>";
你的解决方案: 如果在输入if条件
后递增计数变量值,则输出将为2<?php
$num = array(4, 25, 60, 7, 8);
$count = 0;
foreach($num as $numbers) {
if (($numbers % 5) == 0) {
$count++;
}
}
echo $count;
?>
答案 4 :(得分:0)
如果您想要打印数字
canvas.on("mousemove", function(event) {
var canvasWidth = canvas.outerWidth();
var canvasHeight = canvas.outerHeight();
var halfWidth = canvasWidth / 2;
var halfHeight = canvasHeight / 2;
var offsetX = canvas.offset().left;
var offsetY = canvas.offset().top;
// Main vars
var mouseX = event.clientX - offsetX;
var mouseY = event.clientY - offsetY;
var maxDegree = 20 * Math.PI / 180;
var rotationZ = 0;
if (mouseX < halfWidth) {
rotationZ = -1* (halfWidth - mouseX) * (maxDegree / halfWidth);
} else {
rotationZ = (mouseX - halfWidth) * (maxDegree / halfWidth);
}
var rotationX = 0;
if (mouseY < halfHeight) {
rotationX = -1* (halfHeight - mouseY) * (maxDegree / halfHeight);
} else {
rotationX = (mouseY - halfHeight) * (maxDegree / halfHeight);
}
console.log(rotationZ, rotationX);
mshFloor.rotation.set(rotationX, 0, rotationZ);
mshBox.rotation.set(rotationX, 0, rotationZ);
render();
});
或者如果你只需要点数
$a=array(); //initialized empty array
$num = array(4, 25, 60, 7, 8);
foreach($num as $numbers){
if(($numbers % 5) == 0){
$a=$numbers; //store values into the array
}
}
echo count($a); // echo the count of the array
echo implode('<br>',$a);
回显$ a