0

我看过一些答案,但没有一个与我的具体问题有关。我有一个数组,它接受用户输入并按升序对数组进行排序。这一切都很好,我现在希望用户输入一个我可以找到数组索引的数字,如果没有找到该数字,该函数返回 -1。我无法指出错误,我总是得到-1。

任何帮助都非常感谢

这是我收集信息的表格。

<form action="welcome.php" method="POST" value="">
Name: <input type="text" name="fname" value="">
Age: <input type="text" name="age" value="">
Integer :<input type="number" name="integer" value="">

<div class="container">

<p> Please choose numbers: </p>



  <label>First:</label> 
  <input type="number" name="name[]" ><br />
  <label>2nd</label> 
  <input type="number" name="name[]"><br />
  <label>3rd</label> 
  <input type="number" name="name[]" ><br />
  <label>4th</label> 
  <input type="number" name="name[]"><br />
  <label>5th</label> 
  <input type="number" name="name[]"><br />
  <label>6th</label>
  <input type="number" name="name[]"><br />
  <label>7th</label>
  <input type="number" name="name[]"><br />
  <label>8th</label> 
  <input type="number" name="name[]"><br />
  <label>9th</label> 
  <input type="number" name="name[]"><br />
  <label>10th</label> 
  <input type="number" name="name[]"><br />
  <label>Pos Number</label>
  <input type="number" name="pos"><br />


   <input type="submit">


And the index locator:

   Welcome <?php echo $_POST["fname"]; ?>!<br>
   You are <?php echo $_POST["age"]; ?> years old.

    <?php 

   $tmp = trim($_POST['integer']);
   if (!ctype_digit($tmp)) {echo "Input requires an inetger  "  ;}
   else{
   echo "The integer is   ".$_POST["integer"]."<br>";
   }

   echo"You have entered the numbers below <br>";
   $name=$_POST['name'];

   sort($name);

   foreach( $name as $v) {
   print $v."<br>";

   }

   echo "You wish to find the position of ".$_POST['pos']."<br />";




   function search($name,$K){
   $l=0;
   $size=sizeof($name);
   $u=$size-1;
   $m=0;

   while ($l<=$u){
   $m = ($l+$u)/2;
   round($m);
   echo "this is m ".$m;
   if ($name[$m]<$K) {
   $l=$m+1;
   }
   else if ($name[$m]==$K) {
   return $m;

       return $m;
   } else {
   $u=$m-1;
}
   }

   return -1;

}


   $po=$_POST['pos'];

   $b=search($name,$po);

   echo "The position of the entered number is".$b;


   ?>
4

0 回答 0