You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写JavaScript Calc函数实现求解2/c=3类等式的未知变量值

实现方案

我们假设输入的等式仅含c一个未知数,且为简单一元一次运算(无括号、高次项等复杂结构),实现逻辑如下:

  • 按等号拆分等式为左右两部分,去除所有空格简化匹配
  • 识别左半部分c的运算规则,反解出c的取值
function findC(equation) {
  // 拆分等式并移除所有空格
  const [leftExp, rightExp] = equation.split('=').map(item => item.trim().replaceAll(' ', ''));
  const rightNum = Number(rightExp);

  // 匹配c的运算规则,逐个场景求解
  if (leftExp.includes('/c')) {
    // 场景:A / c = B → c = A / B
    const numerator = Number(leftExp.split('/c')[0]);
    return numerator / rightNum;
  }
  if (leftExp.includes('c/')) {
    // 场景:c / A = B → c = A * B
    const denominator = Number(leftExp.split('c/')[1]);
    return denominator * rightNum;
  }
  if (leftExp.includes('*c') || leftExp.endsWith('c')) {
    // 场景:A*c = B 或 Ac = B → c = B / A
    const coefficient = leftExp.includes('*c') 
      ? Number(leftExp.split('*c')[0]) 
      : Number(leftExp.replace('c', ''));
    return rightNum / coefficient;
  }
  if (leftExp.includes('c*')) {
    // 场景:c*A = B → c = B / A
    const coefficient = Number(leftExp.split('c*')[1]);
    return rightNum / coefficient;
  }
  if (leftExp.includes('+c') || leftExp.includes('c+')) {
    // 场景:A + c = B 或 c + A = B → c = B - A
    const constant = leftExp.includes('+c') 
      ? Number(leftExp.split('+c')[0]) 
      : Number(leftExp.split('c+')[1]);
    return rightNum - constant;
  }
  if (leftExp.includes('-c')) {
    // 场景:A - c = B → c = A - B
    const constant = Number(leftExp.split('-c')[0]);
    return constant - rightNum;
  }
  if (leftExp.includes('c-')) {
    // 场景:c - A = B → c = B + A
    const constant = Number(leftExp.split('c-')[1]);
    return rightNum + constant;
  }
  // 复杂场景可自行扩展规则,当前返回NaN
  return NaN;
}

// 测试你给出的示例
console.log(findC("2 / c = 3")); // 输出 0.6666666666666666

如果需要支持括号、多运算组合、高次项等更复杂的等式,可以在上述代码基础上扩展语法解析逻辑即可。

内容的提问来源于stack exchange,提问作者Devlop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:15:03