查找数组中的平均值[重复]

时间:2021-08-17 12:58:39

This question already has an answer here:

这个问题在这里已有答案:

I am trying to find the minimum, maximum and average value in a number array:

我试图在数字数组中找到最小值,最大值和平均值:

I have the following code below:

我有以下代码:

$number = array(15,20,100,10,25,30);

for ($i=0; $i<count($number); $i++){
    //Find maximum number by max function.
    if ($number[$i] == max($number)){
        //Print maximum number.
        $max = $number[$i];
    }

    //Find minimum number by min function.
    elseif ($number[$i] == min($number)) {
    //Print minimum  number.
        $min = $number[$i];
    }
    //Find the average 
    else ($number[$i] == avg($number)){
    //Print average number
        $avg =$number[$i];
    }

}

echo "min value is $min <br/>";
echo "max value is $max <br/>";
echo "average value is $avg </br>";

It seems to be giving me a syntax error on the average part. Please kindly help.

它似乎在平均部分给我一个语法错误。请帮忙。

2 个解决方案

#1


3  

Your for loop is counterproductive here. You're already using almost all the built-in functions you need to get the values you want, but with the for loop, you're using them many more times than necessary. All you need is:

你的for循环在这里适得其反。您已经使用了所需的几乎所有内置函数来获取所需的值,但是使用for循环,您使用它们的次数比必要的多。所有你需要的是:

$max = max($number);
$min = min($number);
$avg = array_sum($number) / count($number);

#2


0  

In PHP, there's no inherent avg() function, but you can get the average easily. Sum up the total as you loop through:

在PHP中,没有固有的avg()函数,但您可以轻松获得平均值。循环时总结总数:

$total = $total + $number[$i];

then divide by the number of values:

然后除以值的数量:

$avg = $total / count($number);

#1


3  

Your for loop is counterproductive here. You're already using almost all the built-in functions you need to get the values you want, but with the for loop, you're using them many more times than necessary. All you need is:

你的for循环在这里适得其反。您已经使用了所需的几乎所有内置函数来获取所需的值,但是使用for循环,您使用它们的次数比必要的多。所有你需要的是:

$max = max($number);
$min = min($number);
$avg = array_sum($number) / count($number);

#2


0  

In PHP, there's no inherent avg() function, but you can get the average easily. Sum up the total as you loop through:

在PHP中,没有固有的avg()函数,但您可以轻松获得平均值。循环时总结总数:

$total = $total + $number[$i];

then divide by the number of values:

然后除以值的数量:

$avg = $total / count($number);