Rather Vi
Rather Vi

Reputation: 87

Using pow() in self-defined function yields different result compared to direct use in main()

The following C program unexpectedly shows different results when pow() is used in main() and when it is used within a user-defined function:

/*****************************************************
 * Compile command:
 *    gcc -Wall -o powhat powhat.c -lm
 *****************************************************/

#include <stdio.h>
#include <math.h>

float topowerof3(float f) {
    f = pow(f,3);
    return f;
}

int main() {
    printf("275 to the power of 3:\n");
    printf("topowerof3(): %f\n", topowerof3(275));
    printf("pow()       : %f\n", pow(275,3));
    return 0;
}

The output looks like this:

275 to the power of 3:
topowerof3(): 20796876.000000
pow()       : 20796875.000000

Any hints why topowerof3() fails?

Upvotes: 0

Views: 49

Answers (1)

gulpr
gulpr

Reputation: 4588

float != double

float has much lower precision than double.

Change function return type and parameter do double and you will get the same results

double topowerof3(double f) {
    f = pow(f,3);
    return f;
}

int main() {
    printf("275 to the power of 3:\n");
    printf("topowerof3(): %f\n", topowerof3(275));
    printf("pow()       : %f\n", pow(275,3));
    return 0;
}

(C)www.geeksforgeeks.org *scanf (not printf) format specifier

https://godbolt.org/z/WxocvEbv7

Upvotes: 2

Related Questions