HTML,JS Logic无法正常工作

时间:2017-05-29 15:23:02

标签: javascript html math web logic

我正在尝试创建一个js逻辑函数来解决这样的等式中的变量:2x + 5x = 16。问题是它应该输出x = 3 y = 2,而是输出x = -11 y = 1。 I am using 2x+5y=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>

2 个答案:

答案 0 :(得分:0)

因为如果

nx + ky = a和x = a / n,

ky = a-(na)/ n = 0,

但如果 x = f,y =(a-nf)/ k。

对于具有两个未知数的线性函数,您有无数的解决方案。

答案 1 :(得分:0)

你知道有无数的解决方案吗?

任何给定的X和y,sastisfy x = 8 - 2.5y都是真的吗?事​​实上你可以编程修复y = 0的算法,你将获得x = 8.

所以你可以输入两组xy解决方案,或者你有无限的答案。

作为一个拇指规则,你需要与变量一样多的方程式

PD:我真的不知道你在循环中做了什么

相关问题