Home > Enterprise >  The c code for power function is giving wrong result for particular value
The c code for power function is giving wrong result for particular value

Time:08-26

#include <stdio.h>
#include <math.h>
int main()
{
    int base, exponent;
    printf("Enter the value of base: ");
    scanf("%d", &base);

    printf("Enter the value of exponent: ");
    scanf("%d", &exponent);

    int power = pow(base, exponent);
    printf("%d", power);
    return 0;
}

The code when run gives correct value for all the input except when base=5 and exponent=4. The answer comes is 624 but it should be 625.

CodePudding user response:

This is caused by a deficient implementation of pow. Although the correct result, 625, is representable, it is returning 624.9999999999998863131622783839702606201171875.

pow is a difficult function to implement well, and some implementations do not return correct results even when the exact real-number-arithmetic result is representable in the double format. The function is implemented using approximations, and sometimes those approximations produce inaccurate results.

If you change the code to:

double power = pow(base, exponent);
printf("%g\n", power);
printf("%.99g\n", power);

you will see output like:

625
624.9999999999998863131622783839702606201171875

The first line shows the result rounded to six significant decimal digits (the default for a g conversion) and then trimmed of trailing zeros. The second line shows the exact value. (Some C implementations may also fail to show the exact value in this line, but they should show you enough to distinguish it from 625.)

When 624.9999999999998863131622783839702606201171875 is converted to int, the fraction part is discarded, leaving 624. This explains the output you observed.

  •  Tags:  
  • c
  • Related