0

I'm trying to recreate a simple project I have in my fundamentals class to javascript (from C++) but sum doesn't add every time the for loop runs. All other parts are ok but sum just lists the numbers in the order I put them in. Any help is appreciated

var num = prompt("Please enter an integer");
var lrg = num;
var sml = num;
var avg = num;
var sum = num;
var cnt = 10;

function runMath () {

for (i = 1; i < 10; i++) {
    var num = prompt("Please enter an integer");

    if (num > lrg) {
        lrg = num;
    } else {
        lrg = lrg;
    }

    if (num < sml) {
        sml = num;
    } else {
        sml = sml;
    }

    sum += num;

}
}

runMath();

avg = sum/cnt;
2
  • prompt returns a string. Commented May 28, 2015 at 18:26
  • Use parseInt() on the return value of prompt. Commented May 28, 2015 at 18:27

2 Answers 2

1

The problem is that prompt() returns a String, whereas you are expecting a number. You can turn this into a number in a few different ways:

parseInt("33") will return 33, instead of "33"

Likewise, shorthand would look like:

+prompt("33") will return 33, instead of "33"

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! Still learning and won't make that mistake again
You're welcome! If this worked for you, please mark my answer as the correct one :)
0

All input is from the prompt() command is a string. You can convert it to an integer using parseInt(), but the user can enter something other than a number, so you will need to check if it isNaN() (is Not a Number), and deal with it differently if it is.

var num = prompt("Please enter an integer");
num = parseInt(num, 10)
if (isNaN(num)) {
  alert ("That's not a number")
  num = 0 // or do something else
}

Caution: typeof NaN will return "number", so you can't rely on that as a test (see NaN)

An explanation of the + in +prompt: Unary plus (+)

1 Comment

Thank you! I'll be sure to add that in

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.