C编程sqrt函数

#include  #include  int main(void) { double x = 4.0, result; result = sqrt(x); printf("The square root of %lf is %lfn", x, result); return 0; } 

此代码不起作用,因为它采用变量的平方根。 如果你将sqrt(x)更改为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$ 

注意: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$ 

解决了。

如果要链接到适当的库(libc.a和libm.a),代码应该可以正常工作。 您的问题可能是您正在使用gcc,而您忘记通过-lm链接libm.a,这会给您一个未定义的sqrt引用。 GCC在编译时计算sqrt(20.0) ,因为它是常量。

尝试用它编译它

 gcc myfile.c -lm 

编辑:更多信息。 当您使用sqrt调用中的常量替换x时,可以通过查看生成的程序集来确认这一点。

 gcc myfile.c -S 

然后看看myfile.s中的程序集,你不会在任何地方看到行call sqrt

你应该这样做:

 root@bt:~/Desktop# gcc -lm sqrt.c -o sqrt root@bt:~/Desktop# ./sqrt The square root of 4.000000 is 2.000000n root@bt:~/Desktop#