JS simple math task (raising an inputed number to a power)

Viewed 54

I have a task in js. My program should take a number from a user and put it into power that is also inserted. I have coped with positive powers but the algorithm for negative ones always gives a positive answer and after putting an option for a zero power every variant somehow returns -1; Please help me find an error.

function powX(x, pow) {
  x = +prompt('Insert a number: ');
  pow = +prompt('Insert a power: ');
  var result;
  if (x > 0) {
    var result = x;
    for (i = 1; i < pow; i++) {
      result *= x;
    }
  }
  if (x < 0) {
    var result = x;
    for (i = 1; i < Math.abs(pow); i++) {
      result /= x;
    }
  } else {
    result = 1;
  }

  return result;
}

console.log(powX());

2 Answers

There are few mistakes in the code:

  • You should use else-if instead of if in your second block.
  • You should check pow instead of x
  • You are not using var or let with i so it will become global variable. Use let or var
  • You are using var again inside your if blocks but variables declared with var have function scope so it will not throw error. But with let it will break your code. Don't redeclare result again and again.

function powX(x, pow) {
  x = +prompt('Insert a number: ');
  pow = +prompt('Insert a power: ');
  var result;
  if (pow > 0) {
    result = x;
    for (let i = 1; i < pow; i++) {
      result *= x;
    }
  }
  else if (pow < 0) {
    result = x;
    for (let i = 0; i <= Math.abs(pow); i++) {
      result /= x;
    }
  } else {
    result = 1;
  }

  return result;
}

console.log(powX());

You don't need two loops one to divide and other using multiply. Just calculate the result just by multiplying and at the end multiply the result with x or divide it based on condition.

function powX(x, pow) {
  x = +prompt('Insert a number: ');
  pow = +prompt('Insert a power: ');
  if(pow === 0) return 1;
  var result = x;
  for (let i = 1; i < Math.abs(pow); i++) {
    result *= x;
  }
  return pow < 0 ? (x/result/x) : result; 
}

console.log(powX());

Use an else if for your second condition, otherwise, its else block will always be executed for x > 0, setting your result to 1.

function powX(x, pow) {
  x = +prompt('Insert a number: ');
  pow = +prompt('Insert a power: ');
  var result;
  if (x > 0) {
    result = x;
    for (i = 1; i < pow; i++) {
      result *= x;
    }
  }
  else if (x < 0) {
    result = x;
    for (i = 1; i < Math.abs(pow); i++) {
      result /= x;
    }
  } else {
    result = 1;
  }

  return result;
}

console.log(powX());

Also, it'll look better if you remove the re-declaration of result in the if and else if blocks. It won't affect your output but still.

Note: As @ASDFGerte correctly pointed out in the comments, OP's code has other flaws, but I think this still answers his main concern and actual question.

Related