Student Average
PHP
Easy
8 views
Problem Description
Create a Student class that stores marks and prints average with 2 decimals.
Input Format
First n. Next line n marks.
Output Format
One number with 2 decimals.
Official Solution
<?php
class Student{
private $marks=[];
function add($m){ $this->marks[]=$m; }
function avg(){
if(!count($this->marks)) return 0.0;
$sum=0.0;
foreach($this->marks as $m) $sum+=$m;
return $sum/count($this->marks);
}
}
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$st=new Student();
for($k=0;$k<$n;$k++) $st->add(floatval($tokens[$i++] ?? 0));
echo number_format($st->avg(),2,'.','');
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!