var x, y, z, r1, r2, a, b,
eq = "2 * x + 3 * y - z = 0;";
console.clear();
eq = eq.replace(" = 0;", "");
y = 12; z = 34;
x = 1; r1 = eval(eq);
x = 2; r2 = eval(eq);
a = r2 - r1; b = r1 - a; x = -b / a;
console.log(x);
或者,如果您需要将解决方案公式作为字符串:
var eq = "2 * x + 3 * y - z = 0;", eq2,
match, a, b, c, x, y, z;
function process(prefix) {
prefix = prefix.replace(/[\s\*]/g, "");
switch (prefix) {
case "" : return +1;
case "+": return +1;
case "-": return -1;
default : return +prefix;
}
}
console.clear();
match = eq.match(/^([^x]*)x([^y]*)y([^z]*)z ?= ?0;$/);
if (match === null || match.length !== 4)
console.log("Invalid equation");
else {
a = process(match[1]);
b = process(match[2]);
c = process(match[3]);
eq2 = "(" + (-b) + " * y + " + (-c) + " * z) / " + a;
console.log(eq2);
y = 12; z = 34;
x = eval(eq2);
console.log(x);
}
eq2
将会(-3 * y + 1 * z) / 2