Why pow(10,5) Displays 9,999 Instead of 10,000 in C
In C , when using the pow() function with integer inputs and floating-point exponents, unexpected results can occur due to the representation of floating-point values. Specifically, pow(10.0, 5) may result in a value of 9999.9999999 or similar. When this floating-point value is assigned to an integer variable, it is truncated.
For instance, consider the following code snippet:
const int sections = 10; for(int t = 0; t < 5; t++){ int i = pow(sections, 5- t -1); // <-- pow() with integer base, floating-point exponent cout << i << endl; }
The output of this code will incorrectly display:
9999 1000 99 10 1
However, if the code is modified to use the pow() function directly in the cout statement, the expected results are obtained:
for(int t = 0; t < 5; t++){ cout << pow(sections,5-t-1) << endl; // <-- pow() used directly in cout }
With this modification, the output will correctly display:
10000 1000 100 10 1
This discrepancy occurs because in the first example, the floating-point result of pow(sections, 5- t -1) is truncated when assigned to an integer variable. In the second example, however, the floating-point result is rounded when passed directly to cout, resulting in the correct display.
The above is the detailed content of Why Does `pow(10, 5)` Sometimes Return 9999 Instead of 10000 in C ?. For more information, please follow other related articles on the PHP Chinese website!