Ad

Function Variables Dont Change From Initial Value , No Idea Why

- 1 answer

in the following function maxnum and minnum always stay at their infinity value and don't get the value they should in the while loop, so when i log it to the console it says infinity and -infinity respectively, any ideas?

// Read 10 numbers and print
// :a.The maximum number.b.The minimum number.c.The average
printMaxMinSum();

function printMaxMinSum() {
  var numsCount = 10
  var count = 0;
  var sum = 0
  // var inputNumber = +prompt('Enter your number')
  var minNum = Infinity
  var maxNum = -Infinity


  while (count < numsCount) {
    debugger
    var inputNumber = +prompt('Enter your number')
    if (minNum < inputNumber) minNum = inputNumber
    if (maxNum > inputNumber) maxNum = inputNumber
    sum += inputNumber
    count++
  }

  var avg = sum / numsCount
  console.log('The higest number is: ', maxNum, 'the lowest number is: ', minNum, 'the average is: ', avg)
  console.log('avg is', avg)
}

Ad

Answer

Look at these lines:

if (minNum < inputNumber) minNum = inputNumber
if (maxNum > inputNumber) maxNum = inputNumber

Think about the logic: minNum < inputNumber will always be false because minNum is Infinity (which is always larger than any number).

The same for the second line because maxNum is -Infinity which is always less than any number.

Reverse the logic:

if (inputNumber < minNum) minNum = inputNumber
if (inputNumber > maxNum) maxNum = inputNumber
Ad
source: stackoverflow.com
Ad