C编程sqrt函数 [英] C programming sqrt function

查看:180
本文介绍了C编程sqrt函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

,因为它正在一个变量的平方根这code不起作用。如果你改变了的sqrt(x)的,到的sqrt(20.0)中,code工作得很好,为什么?请解释一下。

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$ ./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。

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$ 

解决。

推荐答案

在code。如果是在适当的库(的libc.a和libm.a)链接应该只是罚款。您的问题可能是,你正在使用gcc,你就忘记通过 -lm ,这是给你一个未定义的参考开方在libm.a链接。 GCC计算的sqrt(20.0)在编译时间,因为它是一个常数。

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.

试着用编译它

gcc myfile.c -lm

编辑:一些更多的信息。您可以通过查看生成的汇编证实了这一点,当你在开方调用一个常数替换x。

gcc myfile.c -S

然后参加 myfile.s的一看装配和你将看不到行调用sqrt 的任何地方。

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

这篇关于C编程sqrt函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆