Running Average
PHP
Medium
4 views
Problem Description
Given n numbers, print the running average after each number (2 decimals).
Input Format
First line n. Next line n ints.
Output Format
n lines averages.
Sample Test Case
Output:
10.00
15.00
20.00
25.00
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$sum=0.0; $output=[];
for($k=1;$k<=$n;$k++){
$sum+=floatval($tokens[$i++] ?? 0);
$output[] = number_format($sum/$k,2,'.','');
}
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!