lundi 29 mai 2017

HTML, JS Logic not working

I am trying to create a js logic function to solve the variables in an equation like this: 2x+3x=16. The problem is that it is supposed to output x=3 y=2, but instead, it outputs x=-10 y=2. enter image description here I am using 2x+3y=16 for this result.

function solver(){
  //Get c1, c2, and the answer
  var c1=parseInt(prompt("Enter the coefficient of x:", "Example: 2 if you have 2x"));
  var c2=parseInt(prompt("Enter the coefficient of y:", "Example: 3 if you have 3y"));
  var answer=parseInt(prompt("Enter the answer:", "Example: 2x=4 it would be 4"));
  //set other variables
  var x;
  var y;
  var m;
  //setup
  x=answer/c1;
  m=answer%c1;
  //loop
  while(true){
    //if it is not an integer or it is 0
    if (isInt(m/c2) === false || m/c2 == 0){
      x=x-1;
      m=answer%x;
    }else if (isInt(m/c2)===true && m/c2 != 0){
      x=x;
      y=m/c2;
      break;
    }
  }
  alert("x="+x+" y="+y);
}
function isInt(n) {
   return n % 1 === 0;
}
<h1>EXAMPLE: 2x+5y=16</h1>
<button onclick="solver()">Solve!</button>



Aucun commentaire:

Enregistrer un commentaire