为什么即使在使用%f时pow也会输出0?
我对 c 完全陌生,所以我在学习教程时尝试使用 pow 函数。在教程中(我完全按照他们编写的代码操作),他们的输出是正确的,但我得到的只是 0.000000。有谁知道为什么会这样?
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("%f", pow(4, 3));
return 0;
}
输出
0.000000
回答
插入#include <math.h>,在编译器中打开警告,注意警告消息,并将警告提升为错误。
没有<math.h>,pow未声明,pow(4, 3)并将参数作为 传递int。pow需要将其参数传递为 as double,传递 as时的行为int未由 C 标准定义。此外,pow将假定的返回类型为int,但实际返回类型为double,并且也未定义具有此不匹配的函数调用的行为。并且int为printf转换传递值%f也具有 C 标准未定义的行为。
- @MatheusRossiSaciotto: GCC likely has some built-in knowledge of `pow`. Because it is reserved for use as an external identifier, using it (as an external identifier) for anything other than the standard library `pow` has undefined behavior, so the compiler is not bound by the normal rules for undeclared or unprototyped functions—it can implement whatever behavior it pleases.
- @MatheusRossiSaciotto: If a function is declared with a prototype (parameter declarations), arguments will be converted to the types of the parameters. When a function is not declared (or has `...` for variable arguments), the default argument promotions are used. These perform the integer promotions and promote `float` to `double`, but they do not promote `int` to `double`. So `pow(4, 3)` with no declaration of `pow` passes `int` arguments without any conversion.