我要做一個自動解方程

主控臺


"Error solving equation: Invalid left hand side of assignment operator = (char 5)
Return:a + 27 = 0"



<html>
<head>
  <meta name="description" content="math.js | basic usage">
  <title>math.js | basic usage</title>
  <script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>
</head>
<body>
  <script>
    function solveEquation(equationString, variableRange = { start: -10, end: 10, step: 0.1 }) {
  if (typeof equationString !== 'string') {
    throw new Error('Equation must be a string');
  }

  const equation = equationString.replace(/\s/g, '');
  const variables = equation.match(/[a-zA-Z]+/g);

  if (!variables) {
    throw new Error('No variables found in equation');
  }

  const parser = math.parser();
  variables.forEach(variable => {
    parser.evaluate(`${variable} = ${variableRange.start}:${variableRange.step}:${variableRange.end}`);
  });

  let result;
  try {
    result = parser.evaluate(equation);
  } catch (error) {
    throw new Error('Error solving equation: ' + error.message + "\nReturn:" + equationString);
  }

  return result;
}

const equationString = "a + 27 = 0";

try {
  const result = solveEquation(equationString);
  console.log("方程的解为:", result);
} catch (error) {
  console.error(error.message);
}

  </script>
</body>
</html>

共有 3 則留言

稍微看了一下 math.js 的文件

https://mathjs.org/docs/expressions/parsing.html

evaluate() 裡面要傳的參數是 scope 而不是 equation 吧

感覺這邊用法就錯了,從這邊除錯試試看

我主要是想寫個解方程式的程式碼

看得出來,但是光那個 function 的用法就錯了,當然會有 bug

一個一個問題處理,先試試看解決那個 function 的寫法問題?