Home >Backend Development >C++ >Why Does Integer Division Result in Zero?
Unexpected Zero in Division: A Common Pitfall
Unexpected zeroes from division calculations are a frequent source of programming errors. Let's examine a common scenario to understand why this happens.
The Problem:
Consider this code:
<code class="language-c#">decimal share = (18 / 58) * 100;</code>
The result of this division is surprisingly zero.
The Solution:
The root cause is integer division. When dividing integers, the result is truncated (the fractional part is discarded), leading to a whole number result. In this case, 18 divided by 58 is less than 1, so it's truncated to 0.
To correct this, we must explicitly use decimal values:
<code class="language-c#">decimal share = (18m / 58m) * 100m;</code>
The m
suffix designates each number as a decimal literal, ensuring floating-point division and a precise, non-zero result. This forces the calculation to use floating-point arithmetic, providing the accurate fractional answer.
The above is the detailed content of Why Does Integer Division Result in Zero?. For more information, please follow other related articles on the PHP Chinese website!