Home >Backend Development >C++ >Why Does `pow(10, 5)` Sometimes Return 9999 in C ?
In C , using pow(10, 5) to calculate 10 raised to the power of 5 can occasionally result in an unexpected value of 9,999. This behavior is not consistent and can lead to confusion, as demonstrated in the following code snippet:
const int sections = 10; for (int t = 0; t < 5; t++) { int i = pow(sections, 5 - t - 1); cout << i << endl; }
The expected output of this code is [10000, 1000, 100, 10, 1], but it actually produces [9999, 1000, 99, 10, 1].
The cause of this issue lies in the floating-point representation of pow(10.0, 5) in C . When the result of this calculation is stored in a double-precision floating-point variable, it may contain fractional parts. When it is then assigned to an integer variable, the fractional part is truncated, resulting in a value that is slightly less than the actual answer. In this case, pow(10.0, 5) may be represented internally as 9999.9999999, which gets truncated to 9999 when assigned to an integer.
To avoid this problem, one can use the following alternatives:
The above is the detailed content of Why Does `pow(10, 5)` Sometimes Return 9999 in C ?. For more information, please follow other related articles on the PHP Chinese website!