PDA

View Full Version : Sum of int not working

renzocj
12-26-2011, 10:06 PM
This is not working, any idea ?

function respuestas1() {
var values;
for (var i=0; i<radios.length; i++) {
sum = 0;
for (var i=0; i<values.length; i++) {
sum = sum + Number(values[i]);
}
}
}
}

Apothem
12-26-2011, 10:11 PM
It may have something to do with the fact that you're using a triple equal "operator" (I believe its not a valid operator).

renzocj
12-26-2011, 10:13 PM
It's the "strict equal operator" and only returns a Boolean true if both the operands are equal and of the same type.

Apothem
12-26-2011, 10:26 PM
Didn't think JS had that. Well, the other "problem" I see is that sum was not declared as a variable.

renzocj
12-26-2011, 10:30 PM
Function still not working, the result is a eternal loop-

Apothem
12-26-2011, 10:37 PM
Ah right. I can't believe I forgot that. Your inner loop is reusing the variable "i". Change it to something like "j".

jmrker
12-26-2011, 10:43 PM
Try this...

function respuestas1() {
var sum = 0;
for (var i=0; i<radios.length; i++) {
sum += Number(radios[i].value); // assumes numbers are in radio button values
}
}
return sum;
}

renzocj
12-26-2011, 10:57 PM
Thank you now I have the total sum, just in case do you know what I would have to do if I wanted to have an average ? Let's say I have more groups of radio buttons ...

Thanks for all the support!

Apothem
12-26-2011, 11:01 PM
Divide the sum by radios.length

jmrker
12-26-2011, 11:03 PM
Nearly the same code...

function respuestas1() {
var sum = 0;
for (var i=0; i<radios.length; i++) {
sum += Number(radios[i].value); // assumes numbers are in radio button values
}
}
var average = sum / (radios.length+1); // assumes length value is NOT zero
alert('Sum is: '+sum+'\nAverage: '+average);
return sum;
}

If you need only the averages of the buttons checked, that could be done as well.
Give it a shot yourself if you want to learn.
If not, then just post "I give up!"

Major problem with averages of radio buttons is that only ONE button can be checked in a group.
You would need to change to checkboxes if you want an average of more than one button.