简体   繁体   English

C编程sqrt函数

[英]C programming sqrt function

#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; 
} 

This code does not work because it is taking the square root of a variable. 此代码不起作用,因为它采用变量的平方根。 If you change the sqrt(x) , to sqrt(20.0) , the code works just fine, why? 如果你将sqrt(x)更改为sqrt(20.0) ,代码工作得很好,为什么? Please explain. 请解释。

Also, how do I get the square root of the variable (which is what I really need)? 另外,我如何获得变量的平方根(这是我真正需要的)?

OUTPUT: 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$ 

NOTE:sqroot1 is the sqroot of 20.0. 注意:sqroot1是20.0的sqroot。 sqroot2 is the sqroot of a variable. 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$ 

SOLVED. 解决了。

The code should work just fine if you are linking in the proper libraries (libc.a and libm.a). 如果要链接到适当的库(libc.a和libm.a),代码应该可以正常工作。 Your issue is probably that you are using gcc and you are forgetting to link in libm.a via -lm , which is giving you an undefined reference to sqrt. 您的问题可能是您正在使用gcc,而您忘记通过-lm链接libm.a,这会给您一个未定义的sqrt引用。 GCC calculates the sqrt(20.0) at compile time because it is a constant. GCC在编译时计算sqrt(20.0) ,因为它是常量。

Try to compile it with 尝试用它编译它

gcc myfile.c -lm

EDIT: Some more information. 编辑:更多信息。 You can confirm this by looking at the generated assembly when you replace x with a constant in the sqrt call. 当您使用sqrt调用中的常量替换x时,可以通过查看生成的程序集来确认这一点。

gcc myfile.c -S

Then take a look at the assembly in myfile.s and you will not see the line call sqrt anywhere. 然后看看myfile.s中的程序集,你不会在任何地方看到行call sqrt

You should do it like this: 你应该这样做:

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# 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM