Hi there, I have searched a bit trying to find something similar to this exercise problem, but did not find. Therefore, I signed up and here I am.
Here is the problem instructions:
You need to calculate the average of a collection of values. Every value will be valid number. The average must be printed with two digits after the decimal point. Input
On the first line, you will receive N - the number of the values you must read
On the next N lines you will receive numbers. Output
On the only line of output, print the average with two digits after the decimal point. Example Input - 3 ___ 2.5, 1.25, 3 = Example Output 2.25
I don’t seem to succeed in connecting the input of 3 numbers and the three numbers itself. I have tried different cases but at best received 1 out of 5 correct. Here is the code itself.
let input = 3;
let numbers = [2.5, 1.25, 3];
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
console.log((total / input).toFixed(2));
It comes from Telerik Academy in Bulgaria. I think it changes the input with 4, 3 (where I pass), 3 (again), 5 and 2. I receive the following as a result.
The other example input is 4 __ 1, 1, 1, 1 with output 1 (obviously). But what are the others I don’t know.
I assume that as a function it will look something like this:
let input = 4;
let numbers = [
2.5,
1.25,
3,
];
//let inputGets = + gets();
function average(input) {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return((total / input).toFixed(2));
}
console.log(average(input));
@ilenia in the software that I submit there is a little catch. You need to define the number with +gets(); and since I did not know how to define the array…all problems came from there. With this code, now everything is passed.
let input = [
'3',
'2.5',
'1.25',
'3',
];
let numbers = + gets();
let total = 0;
let arr = [];
for (let i = 0; i < numbers; i++) {
arr[i] = +gets();
}
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
console.log((total / arr.length).toFixed(2));