Reputation: 13216
My code runs well up until the point it is expected to return the result - it does not add up any of the values entered by the user.
a = (prompt("a:"));
b = (prompt("b:"));
c = (prompt("c:"));
negativeSum = Number(0);
positiveSum = Number(0);
var test = [a, b, c];
for (i = 0; i < test.length; i++) {
if (isNaN(test[i])) {
alert(test[i] + " : incorrect input.");
}
else
if (test[i] < 0) {
alert(test[i] + " : positive.")
negativeSum = Number(test[i]++);
}
else {
alert(test[i] + " : positive.")
positiveSum = Number(test[i]++);
}
}
alert(positiveSum + " : sum of +ve elements");
alert(negativeSum + " : sum of -ve elements");
Upvotes: 1
Views: 816
Reputation: 124
isn't sum of negatives always less then sum of positives. if you speaking about absolute diff. than try
if (test[i] < 0) {
alert(test[i] + " : positive.")
negativeSum += Number(test[i]);
}
else {
alert(test[i] + " : positive.")
positiveSum += Number(test[i]);
}
//after the loop
return Math.abs(negativeSum) > positiveSum;
Upvotes: 2
Reputation: 160211
You're not summing anything, you're incrementing each number you've input. You want positiveSum += (each number).
You should also convert the element to a number before doing the comparison to zero and the rest.
Upvotes: 1
Reputation: 499092
Several things - no need for Number(0)
- just using 0
will do.
The line:
positiveSum = Number(test[i]++);
Simply assigns the value of test[i]
+ 1 (this is what the post increment ++
operator does) to positiveSum
. It doesn't add it up to positiveSum
(same is true for negativeSum
.
This should work better:
negativeSum = 0;
positiveSum = 0;
var test = [a, b, c];
for (i = 0; i < test.length; i++) {
if (isNaN(test[i])) {
alert(test[i] + " : incorrect input.");
}
else
if (test[i] < 0) {
alert(test[i] + " : positive.")
negativeSum += test[i];
}
else {
alert(test[i] + " : positive.")
positiveSum += test[i];
}
}
In my code the line:
negativeSum += test[i];
Is equivalent to:
negativeSum = negativeSum + test[i];
Upvotes: 1