Home >Backend Development >C++ >How do we obtain a floating-point result from integer division in C without altering the integer variables?
Floating-Point Precision in Integer Division
In C , integer division often rounds the result down to the nearest integer. However, some operations require fractional precision. How can we obtain a floating-point result without modifying the integer variables?
Consider the following C code:
int a = 10, b = 3; float ans = (a / b);
Despite setting floating-point formatting, the a / b expression truncates the result to 3.
The solution lies in type casting the operands to floats:
float ans = (float)a / (float)b;
By converting the integers to floats before division, the result maintains floating-point precision, as demonstrated by the following output:
3.333
The above is the detailed content of How do we obtain a floating-point result from integer division in C without altering the integer variables?. For more information, please follow other related articles on the PHP Chinese website!