This section introduces you to the exercises of PHP arrays and uses an example of averaging with a one-dimensional array for your reference.
Requirements: Enter 5 numbers in the input box (separate the 5 numbers with spaces), please use a one-dimensional array to write a program to find their average (retaining 2 decimal places). Review: Basic tutorial for getting started with php - php array exercises The code is as follows: <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > </head> <body> <h3>请输入5个数,并且用空格隔开_bbs.it-home.org</h3> <?php /** * php 数组练习 */ //接收提交(输入过来的值) REQUEST $grade =@$_REQUEST['grade']; //echo $grades; //拆分成数组 $grades = explode(" ",$grade); //print_r($grades); //定义一个变量存放总数 $total=0; //计算总分 for($i=0;$i<count($grades);$i++){ $total +=$grades[$i]; } //round函数 保留小数位||这是四舍五入法保留2位小数 //echo '平均数为:'.round($total/count($grades),2); ?> <form action="array01.php" method="post"> 请输入:<input type="text" name="grade" value="<?php echo $grade;?>"> <input type="submit" value="请提交"> </form> <?php //number_format()函数 是保留位数,同时格式化数字加千位符 echo '平均数为:'.number_format($total/count($grades),2); //echo '平均数为:'.round($total/count($grades),2); ?> </body> </html> Copy after login Thank you for paying attention to the PHP introductory tutorials. This series of PHP basic tutorials will help PHP newbies quickly master the PHP programming language. Programmer's Home will continue to launch PHP-related tutorials for everyone, and I wish you all the best in your learning and progress! |