• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

147
Vistas
JavaScript how to ensure sum of two numbers is not negative

I am creating a math game for kids using JavaScript and created a function that will generate two numbers, first number is positive and second is negative so that students will have to sum the given two number, but i want to generate numbers that the sum will not be a negative number.

my current functions

function randomIntFromInterval(min, max) { // min and max included 
    return Math.floor(Math.random() * (max - min + 1) + min)
}

function generateRandomSubtractNumber() {
    var base_number = randomIntFromInterval(2, 10)
    var sub_number = -randomIntFromInterval(1, 5);
    console.log(base_number, sub_number)
    return  {
        "base_number" : base_number,
        "sub_number" : sub_number,
        "total" : base_number +  sub_number 
    }
}

I tried to put an if statement to check if the object.total will be less than zero but not sure how to re-generate again if the statement is true.

about 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think you can pass base_number as param to randomIntFromInterval.

 var base_number = randomIntFromInterval(2, 10)
 var sub_number = -randomIntFromInterval(1, base_number);
about 3 years ago · Juan Pablo Isaza Denunciar

0

function generateRandomSubtractNumber() {
    var base_number = randomIntFromInterval(2, 10)
    var sub_number = randomIntFromInterval(1, 5);
    return   base_number >= sub_number?

    {
        "base_number" : base_number,
        "sub_number" : -sub_number,
        "total" : base_number - sub_number 
    }:
   
   {
        "base_number" : sub_number,
        "sub_number" : -base_number ,
        "total" : sub_number - base_number 
    }
}
about 3 years ago · Juan Pablo Isaza Denunciar

0

I see 2 solutions for this :

  • The first one is to do a while loop which regenerate these numbers while the sum is negative
  • The second one (better) is to generate the second between 1 and the first number, this way the first one (positive) is always greater than the second one (negative)
about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda