dongxian6741 2016-02-10 03:21
浏览 755
已采纳

通过for循环查找数组中的最大值和最小值

I want to find the maximum and minimum value by the for loop, but problem is that when array value is start from a maximum number like (100,30,50,60) then output is the correct first maximum value then, minimum value.

Otherwise output first minimum value, then maximum value.

any idea?

    //Number serial.
    $number = array(10,15,20,100,25,30);

    for ($i=0; $i<count($number); $i++){
        //Find maximum number by max function.
        if ($number[$i] == max($number)){
            //Print maximum number.
            echo " The max number is $number[$i] <br>" ;
        }
        //Find minimum number by min function.
        elseif ($number[$i] == min($number)) {
            //Print minimum  number.
            echo " The min number is $number[$i] <br>";
        }
    }
//Output: 
//The min number is 10
//The max number is 100 

When array value is start from a maximum number.

 //Number serial.
    $number = array(100,10,15,20,25,30);

    for ($i=0; $i<count($number); $i++){
        //Find maximum number by max function.
        if ($number[$i] == max($number)){
            //Print maximum number.
            echo " The max number is $number[$i] <br>" ;
        }
        //Find minimum number by min function.
        elseif ($number[$i] == min($number)) {
            //Print minimum  number.
            echo " The min number is $number[$i] <br>";
        }
    }
//Output:
//The max number is 100
//The min number is 10
  • 写回答

2条回答 默认 最新

  • duangelin7513 2016-02-10 03:30
    关注

    Actually I think you dont need the for loop to begin with.... You can do something simple like this:

    $number = array(15,20,100,10,25,30);
    $max = max($number);
    $min = min($number);
    echo "min value is $min <br/>";
    echo "max value is $max <br/>";
    

    Update:

    But if you want to flexibly, echo the statements according to the index of the min and max values then you can do something like this:

    $number = array(15,20,100,10,25,30);
    $max = max($number);
    $min = min($number);
    $max_idx = array_search($max,$number);
    $min_idx = array_search($min,$number);
    if($max_idx < $min_idx){
      echo "max value is $max 
    ";
      echo "min value is $min 
    ";
    }else{
      echo "min value is $min 
    ";
      echo "max value is $max 
    ";
    }
    

    What this will do is, it will get the indices of the min and max values and depending on which is encountered first, it will print that statement first.

    Hope it helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?