0

I'm trying to write a function (GetPositiveInteger) that generates a random integer between variables a and b. if a > b, it's supposed to switch the values of the two so that b=>a before generating the Number.

I don't know if I'm misunderstanding the question or what because I can't figure out where I'm meant to be converting a and b to integers and my program keeps just returning NaN. here's my code maybe someone could take a look at it?

function GetRandomInteger(a, b, c) {
  a = Number(a), b = Number(b);
  if (a > b) {
    var a = 2,
      b = 1,
      c = a;
    a = b;
    b = c;
  } else {
    var x = parseInt(Math.random() * b) + a;
  }

  return x;
}

let x;
console.log(Number(GetRandomInteger(x)));

8
  • Why are you setting a = 2 and b = 1? Commented Feb 9, 2021 at 2:27
  • What is the c parameter for? Commented Feb 9, 2021 at 2:28
  • 1
    The function takes 3 arguments, you're calling it with only 1. You also never set x before calling the function. Commented Feb 9, 2021 at 2:29
  • So I could switch the value of a and b if a was higher than b I thought that was what we're supposed to do? This question is so convoluted lol I hate that I'm struggling so much with it Commented Feb 9, 2021 at 2:30
  • 1
    Is it just me or did SO remove the "no homework exercises" rule? Because it's no longer in the list of reasons to flag or close? Commented Feb 9, 2021 at 2:43

1 Answer 1

2

When a > b, you're setting them to specific numbers before swapping them, instead of swapping the original values.

The code that generates the random number shouldn't be in else, because you won't run that after swapping a and b. It should just be after the if.

You don't need the c parameter. Use a temporary variable declared inside the function when swapping.

Use Math.floor() to convert a floating point number to an integer. parseInt() is for parsing strings (it will work in this case because it first converts the float to a string, but it's better to use the more specific function).

You need to call the function with two arguments. In the example below I just hard-coded them, but you can use your function that asks the user for numbers. Just use it twice to set two variables.

function GetRandomInteger(a, b) {
  a = Number(a), b = Number(b);
  if (a > b) {
    let temp = a;
    a = b;
    b = temp;
  }
  var x = Math.floor(Math.random() * b) + a;

  return x;
}

console.log(GetRandomInteger(1, 10));
console.log(GetRandomInteger(15, 3));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.