user10454314
user10454314

Reputation:

Difficulty with finding sum of values

Write a function named "count_in_range" that takes a list of numbers as a parameter and returns the number of values in the input that are between 15.3 and 42.19 not including these end points. (My code below)

function count_in_range(numbers){
    var total = 0;
    for (var i of numbers){
        if (15.3 < i < 42.19){
            total = total + 1;
        }
        return total;
    }
}

Now that I am using JavaScript, I keep on getting 1 instead of the number of values that satisfies the statement.

Upvotes: 0

Views: 295

Answers (2)

ControlAltDel
ControlAltDel

Reputation: 35106

The problem appears to be that your return statement is short circuiting your loop. Below I have fixed this

function count_in_range(numbers){
    var total = 0;
    for (var i of numbers){
        if (15.3 < i < 42.19){
            total = total + 1;
        }
    }
    return total;
}

Upvotes: 1

Chayan
Chayan

Reputation: 614

function count_in_range(numbers){
    var total = 0;
    for (var i of numbers){
        if (i > 15.3  &&  i < 42.19){
            total = total + 1;
        }

   }
return total;
}

Upvotes: 2

Related Questions