Dividing Integers for a Floating-Point Result
Despite the use of a float variable to store the result, integer division can result in a truncated output. To overcome this issue while maintaining the input variables as integers, consider the following solution:
Cast the operands to floats explicitly:
float ans = (float)a / (float)b;
This casting operation forces the compiler to perform floating-point division, ensuring a floating-point result even when the operands are integers. The example below demonstrates the expected behavior:
#include <iostream> #include <iomanip> using namespace std; int main() { int a = 10, b = 3; float ans = (float)a / (float)b; // Explicit casting to floats cout << fixed << setprecision(3); cout << ans << endl; // Floating-point result return 0; }
The above is the detailed content of How to Get a Floating-Point Result from Integer Division in C ?. For more information, please follow other related articles on the PHP Chinese website!