Home >Backend Development >C++ >Why Does Integer Division Return Zero, and How Can I Fix It?
Solving the Zero Division Problem in Integer Math
The expression 18 / 58
evaluates to zero because standard integer division truncates any fractional component. To get the correct decimal result, you need to perform the calculation using floating-point numbers. Here's the corrected code:
<code class="language-csharp">decimal share = (18m / 58m) * 100m;</code>
The m
suffix explicitly casts the integer literals to decimals. This ensures that the division operation maintains the fractional part, yielding the accurate percentage: 18 / 58 * 100 ≈ 31.0344827586207.
The above is the detailed content of Why Does Integer Division Return Zero, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!