PHP计算显示平均温度、五个最低及最高温度

藏色散人
藏色散人 原创
2019-01-29 10:30:12 5585浏览

PHP计算显示平均温度,五个最低及最高温度。记录温度是78,60,62,68,71,68,73,85,66,64,76,63,75,76,73,68,62,73,72,65,74,62,62,65 ,64,68,73,75,79,73。

下面我们就通过具体的代码示例,给大家介绍PHP计算上述记录温度中的平均温度、五个最低及最高温度的方法。

代码示例如下:

<?php
$month_temp = "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73";
$temp_array = explode(',', $month_temp);
$tot_temp = 0;
$temp_array_length = count($temp_array);
foreach($temp_array as $temp)
{
    $tot_temp += $temp;
}
$avg_high_temp = $tot_temp/$temp_array_length;
echo "平均温度为: ".$avg_high_temp."
";
sort($temp_array);
echo " 五个最低温度:";
for ($i=0; $i< 5; $i++)
{
    echo $temp_array[$i].", ";
}
echo "五个最高温度:";
for ($i=($temp_array_length-5); $i< ($temp_array_length); $i++)
{
    echo $temp_array[$i].", ";
}

输出:

平均温度为:70.6                               
五个最低温度:60,62,63,63,64,
五个最高温度:76,78,79,81,85,

相关函数:

explode() 函数表示使用一个字符串分割另一个字符串

count()函数表示计算数组中的单元数目,或对象中的属性个数

sort()函数表示对数组进行排序。当本函数结束时数组单元将被从最低到最高重新安排。

注:

$tot_temp += $temp 相当于 $tot_temp=$tot_temp + $temp

本篇文章就是关于PHP计算显示平均温度、五个最低及最高温度的方法介绍,也是PHP面试常见考点之一,非常简单易懂,希望对需要的朋友有所帮助!

以上就是PHP计算显示平均温度、五个最低及最高温度的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。