题目
假设有一教师依学生座号输入考试分数,现希望在输入完毕后自动显示学生分数的排行,当然学生的分数可能相同
算法:
1、 走访分数阵列A1,获得各分数人数的阵列A2
2、 对A2分数阵列进行向左相加处理,获得最终分数对应的排名
php代码实现如下:
<?php
class score_rank
{
function __construct()
{
define('MAX', 100);
define('MIN', 0);
$score = array_fill(0, MAX+1, 0);
$rank = array_fill(0, MAX+2, 0);
$count = 0;
do
{
echo iconv('utf-8', 'gbk', "请输入分数,以-1结束:\n");
$score[$count++] = trim(fgets(STDIN));
}
while($score[$count-1] != -1);
$count--;
for($i=0; $i<$count; $i++)
{
$rank[$score[$i]]++;
}
$rank[MAX+1] = 1;
for($i=MAX; $i>=MIN; $i--)
{
$rank[$i] = $rank[$i] + $rank[$i+1];
}
echo iconv('utf-8', 'gbk', "得分\t排行\n");
for($i=0; $i<$count; $i++)
{
echo $score[$i]."\t".$rank[$score[$i]+1]."\n";
}
}
}
new score_rank();
转载于:https://blog.51cto.com/hehe1987/1641847