I'm working on this task I've got from school. The program works like this: You pass some numbers seperated by comma, then the program puts the values in an array of integers (parseInt()), then it calls for the calculate function, witch calculates the highest number, the sum, the and the diferance. But the thing is, that the program thinks the variable sum is a string, not a int. So I get sum of 0+1+2 = 012. It's pure javascript btw.
window.onload = start;
var arr = [];
var sum = 0;
var max;
var avg;
function start() {
document.getElementById('sub').onclick = getValues;
}
function getValues() {
var str = document.getElementById('input').value;
arr = str.split(",");
for (var i = 0; i < arr.length; i++) {
parseInt(arr[i]);
}
calculate(arr);
print();
}
function calculate(arr) {
var temp = arr[0];
sum = 0;
for (var i = 0; i < arr.length; i++) {
if (temp < arr[i]) {
temp = arr[i];
}
sum += arr[i];
}
max = temp;
avg = sum / arr.length;
}
function print() {
document.getElementById('div').innerHTML = "In the array of theese values: " + arr + ",<br>is " + max + " the biggest, " + sum + " is the sum, " + " and " + avg + " is the average.";
}
The values in arr
are strings, since they come from split()
Your parseInt()
call does nothing, as you throw away its return. Either save the value:
arr[i] = parseInt( arr[i], 10 );
or coerce to a number when adding:
sum += +arr[i];