Skip to content

运算符 Precedence 错误

快速摘要

你的 表达式 gives 错误 result 因为 运算符 是 evaluated in 顺序 你 做 不 intend.

为什么发生

  • Missing parentheses 到 control evaluation 顺序

  • Assuming 左-到-正确 evaluation for 所有 运算符

  • Mixing 运算符 使用 不同 precedence (e.g., + and *)

最小示例

✗ 错误代码
let avg = 10 + 20 + 30 / 3; // 10 + 20 + 10 = 40, not 20
console.log(avg);
✓ 修复代码
let avg = (10 + 20 + 30) / 3; // 60 / 3 = 20
console.log(avg);

Division 有 higher precedence than addition, 所以 30/3=10 是 computed 首先, 然后 10+20+10=40. Parentheses force addition 首先: (10+20+30)/3=20.

如何诊断

  • Print 中级 值 到 see 什么 是 actually computed

  • 检查 运算符 precedence 表 for 你的 language

  • 添加 parentheses 到 制作 intended 顺序 explicit

如何修复

  • 添加 parentheses 到 enforce desired evaluation 顺序

  • Break 复杂 表达式 到 smaller, named steps

  • Use calculator 到 验证 预期结果

如何预防

  • Use parentheses generously in 复杂 表达式

  • Break 长 表达式 到 中级 变量

相关资源

相关术语

相关课程

← 返回语言