开发者

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? Please explain.

Also, how do I get the square root of the variable (which is what I really need)?

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$ .开发者_如何学JAVA/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. sqroot2 is the sqroot of a variable.

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). 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 calculates the sqrt(20.0) at compile time because it is a constant.

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.

gcc myfile.c -S

Then take a look at the assembly in myfile.s and you will not see the line call sqrt anywhere.


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# 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜