#include <math.h>
#include <stdio.h>
int main(void)
{
double x = 4.0, result;
result = sqrt(x);
printf("The square root of %lf is %lfn", x, result);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码不起作用,因为它采用变量的平方根.如果你改变了sqrt(x),to sqrt(20.0),代码工作正常,为什么?请解释.
另外,我如何获得变量的平方根(这是我真正需要的)?
OUTPUT:
matthewmpp@annrogers:~/Programming/C.progs/Personal$ vim sqroot1.c
matthewmpp@annrogers:~/Programming/C.progs/Personal$ cc -c sqroot1.c
matthewmpp@annrogers:~/Programming/C.progs/Personal$ cc -o sqroot1 sqroot1.c
matthewmpp@annrogers:~/Programming/C.progs/Personal$ ./sqroot1
4.472136
matthewmpp@annrogers:~/Programming/C.progs/Personal$ vim sqroot2.c
matthewmpp@annrogers:~/Programming/C.progs/Personal$ cc -c sqroot2.c
matthewmpp@annrogers:~/Programming/C.progs/Personal$ cc -o sqroot2 sqroot2.c
/tmp/ccw2dVdc.o: In function `main':
sqroot2.c:(.text+0x29): undefined reference to `sqrt'
collect2: ld returned 1 exit status
matthewmpp@annrogers:~/Programming/C.progs/Personal$
Run Code Online (Sandbox Code Playgroud)
注意:sqroot1是20.0的sqroot.sqroot2是变量的sqroot.
matthewmpp@annrogers:~/Programming/C.progs/Personal$ cc -o sqroot2 sqroot2.c -lm
matthewmpp@annrogers:~/Programming/C.progs/Personal$ ./sqroot2
4.472136
matthewmpp@annrogers:~/Programming/C.progs/Personal$
Run Code Online (Sandbox Code Playgroud)
解决了.
Kiz*_*aru 35
如果要链接到适当的库(libc.a和libm.a),代码应该可以正常工作.您的问题可能是您正在使用gcc而忘记在libm.a中链接-lm,这将为您提供对sqrt的未定义引用.GCC计算sqrt(20.0)编译时,因为它是一个常量.
尝试用它编译它
gcc myfile.c -lm
Run Code Online (Sandbox Code Playgroud)
编辑:更多信息.当您使用sqrt调用中的常量替换x时,可以通过查看生成的程序集来确认这一点.
gcc myfile.c -S
Run Code Online (Sandbox Code Playgroud)
然后看一下装配myfile.s,你就不会在call sqrt任何地方看到这条线.