C中的powfunction
我编写了一个具有power.h函数的C代码,该代码来自math.h库。 当我编译我的程序时,我收到一个错误,即“未定义引用’pow’函数”,我使用gcc编译器(fedora 9)编译我的程序。
我将-lm标志插入gcc然后,错误被省略,但pow函数的输出为0。
#include main() { double a = 4, b = 2; b = pow(b,a); }
谁能帮我? 我的编译器有问题吗?
谢谢。
您的程序不输出任何内容。
您所指的0可能是退出代码,如果您没有从main
显式返回,则该代码为0。
尝试将其更改为符合标准的签名并返回b
:
int main(void) { ... return b; }
请注意,返回值基本上限于8位信息,因此非常非常有限。
使用printf
显示值。
#include ... printf("%f\n", b); ...
必须使用浮点转换说明符( f
, g
或e
)来打印double
值。 您不能使用d
或其他人并期望输出一致。 (这实际上是未定义的行为。)
对于寻求这样一个答案的其他人:
这不起作用 :
gcc my_program.c -o my_program
它会产生这样的东西:
/tmp/cc8li91s.o: In function `main': my_program.c:(.text+0x2d): undefined reference to `pow' collect2: ld returned 1 exit status
这将有效 :
gcc my_program.c -o my_program -lm
您缺少printf行来将值打印到stdout。 试试这个:
#include #include int main() { double a=4, b=2, c; c = pow(b,a); printf("%g^%g=%g\n", a,b,c); return 0; }
输出将是:
4^2=16
这里有关于基数和指数的混淆。 这并不是立即显而易见的,因为2 ^ 4和4 ^ 2都相等16。
void powQuestion() { double a, b, c; a = 4.0; b = 2.0; c = pow(b, a); printf("%g ^ %g = %g\n", a,b,c); // Output: 4 ^ 2 = 16 a = 9.0; b = 2.0; c = pow(b, a); printf("%g ^ %g = %g\n", a,b,c); // Output: 9 ^ 2 = 512 >> Wrong result; 512 should be 81 << // K & R, Second Edition, Fifty Second Printing, p 251: pow(x,y) x to the y double x, y, p; x = 9.0; y = 2.0; p = pow(x, y); printf("%g ^ %g = %g\n", x, y, p); // Output: 9 ^ 2 = 81 // even more explicitly double base, exponent, power; base = 9.0; exponent = 2.0; power = pow(base, exponent); printf("%g ^ %g = %g\n", base, exponent, power); // Output: 9 ^ 2 = 81 }