当在 main() 中使用 pow() 以及在用户定义函数中使用 pow() 时,以下 C 程序意外地显示了不同的结果:
/*****************************************************
* 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;
}
输出如下所示:
275 to the power of 3:
topowerof3(): 20796876.000000
pow() : 20796875.000000
有任何提示说明为什么 topowerof3() 失败吗?
float
!=double
float
的精度比 double
低得多。
更改函数返回类型和参数做双倍,你会得到相同的结果
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;
}