Home >Backend Development >C++ >Why Does `pow(10, 5)` Sometimes Return 9999 in C ?

Why Does `pow(10, 5)` Sometimes Return 9999 in C ?

DDD
DDDOriginal
2025-01-01 08:33:10934browse

Why Does `pow(10, 5)` Sometimes Return 9999 in C  ?

Why pow(10,5) May Equal 9,999 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].

Explanation

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.

Solution

To avoid this problem, one can use the following alternatives:

  • Specify the result of pow as a double-precision floating-point value: double i = pow(sections, 5 - t - 1);.
  • Round the result of pow to the nearest integer using the round function: int i = round(pow(sections, 5 - t - 1));.
  • Use a more precise floating-point representation, such as long double or quad double.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn