美好的一天,我的任务是在php中创建一个变量计数器。 我陷入了最后阶段。那就是显示正值的总数。我在php中使用了count(),但它没有给我总数。有没有办法可以得到值为count()的总和?
if ($start < $end)
{
for($ctr = $start; $ctr<=$end; $ctr++)
{
if ($ctr == 0)
{
echo " <br/ >there is a zero <br/ >";
}
else if ($ctr <=0)
{
echo count($ctr) . " negative value" ;
}
else if($ctr >=0)
{
echo count($ctr) . " positive value ";
}
}
答案 0 :(得分:1)
$zero = $pos = $neg = 0;
for($ctr = $start; $ctr<=$end; $ctr++)
{
switch(true){
case $ctr==0: $zero++; break;
case $ctr<0: $neg++; break;
case $ctr>0: $pos++; break;
}
}
if($zero)
echo "there is a zero<br/>";
if($pos)
echo "$pos positive values<br/>" ;
if($neg)
echo "$neg negative values<br/>" ;
更好的方法是没有任何循环:
function test($start, $end) {
echo "Test of [$start, $end]:\n";
if ($isThereZero = $start * $end <= 0) {
echo "There is zero\n";
}
if ($start < 0) {
$negatives = $isThereZero ? -$start : -$start+$end;
echo "$negatives negative values\n";
}
if ($end > 0) {
$positives = $isThereZero ? $end : $end - $start;
echo ($positives)." positive values\n";
}
}
test(-12, 5);
test(-12, -5);
test(5, 12);
test(0, 0);
答案 1 :(得分:0)
试试:
$zer = 0;
$pos = 0;
$neg = 0;
if ($start < $end)
{
for($ctr = $start; $ctr<=$end; $ctr++)
{
if ($ctr == 0)
{
$zer++;
}
else if ($ctr < 0)
{
$neg++;
}
else if($ctr > 0)
{
$pos++;
}
}
echo $zer . " zero value" ;
echo $neg . " negative value" ;
echo $pos . " positive value ";
答案 2 :(得分:0)
只是为了好玩,这可以在没有循环的情况下完成。这有点棘手,也与最初的问题有点远:
<强> Demo 强>
$start = -3;
$end = 5;
echo ($start <= 0 && $end >= 0 ? "1" : "0")." zero value\n";
echo ($start < 0 && $start <= $end ? (-$start-($end > -1 ? 0 : -$end-1)) : "0"). " negative value\n";
echo ($end > 0 && $start <= $end ? ($end-($start < 1 ? 0 : $start-1)) : "0"). " positive value\n";
答案 3 :(得分:-1)
else if($ctr >=0)
{
$cnt++; //or $cnt+=1;
}
然后使用$ cnt ++对正数值进行计数