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?
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;
}