今日已更新 189 条资讯 | 累计 28951 条内容
关于我们

The “3 / 2 * 10 != 10 * 3 / 2” Problem

/u/Mean-Decision-3502 2026年08月07日 05:46 0 次阅读 来源:Reddit r/programming

Coming from school math, it feels pretty strange that: 3 / 2 * 10 != 10 * 3 / 2 This expression can evaluate to true or false depending on the programming language you use. Languages where the two sides are NOT equal Languages where the two sides ARE equal C, C++, C#, Java, Kotlin, Scala, Ruby, Go, D, Rust, Swift, Zig, Odin, V, Fortran, Python 2 Python 3, JavaScript, TypeScript, Dart, R, Lua 5.3+, Perl, MATLAB, Pascal, Mojo, Nim, Crystal, Julia, Haskell Why are the two sides not equal in the languages on the left? On the left side of the expression above, the operation 3 / 2 is evaluated first using integer arithmetic—truncating the fractional part—which results in 1 . This is then multiplied by 10 , giving a result of 10 for the left side. On the right side, 10 * 3 = 30 is the first step. Dividing this by 2 gives 15 . Thus: 10 != 15 These languages prioritize the efficient (fast) execution of expressions over mathematical correctness, as integer arithmetic is significantly faster than floating-point arithmetic. Unfortunately, these languages use the same / operator for both integer and floating-point division, selecting the operation based on the types of the operands. Regrettably, the expression 3 / 2 * 10.0 still yields 10 in most of these languages (and results in a compilation error in Rust). Even though we indicated our intent to use floating-point numbers by writing 10.0 , it is already too late: compilers evaluate 3 / 2 as integer arithmetic in the first step. Expressions like 3.0 / 2 * 10 or 3 / 2.0 * 10 , on the other hand, produce 15 . Thus, depending on the operand types, you end up with either 10 or 15 . This situation becomes even more dangerous when variables are involved in the expression: num / denum * scale != scale * num / denum This can evaluate to true or false depending on the types of the num and denum variables ( float vs. int ). To avoid these pitfalls, developers use type casting: (float)num / denum * scale != scale * (float)num / denum Thi

本文内容来源于互联网,版权归原作者所有
查看原文