sqrt()函数不使用变量参数

Edd*_*ddy 9 c compiler-errors math.h sqrt

我不知道我是否遗漏了一些明显的东西,但似乎我无法计算C中变量的平方根; sqrt()函数似乎只适用于常量.这是我的代码:

#include <math.h>
#include <stdio.h>

int main()
{
    double a = 2.0;
    double b = sqrt(a);
    printf("%f", b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行此程序时,我收到以下错误:

gcc -Wall -o "test2" "test2.c" (in directory: /home/eddy/Code/euler)
/tmp/ccVfxkNh.o: In function `main':
test2.c:(.text+0x30): undefined reference to `sqrt'
collect2: ld returned 1 exit status
Compilation failed.
Run Code Online (Sandbox Code Playgroud)

但是,如果我将sqrt()中的参数替换为常量(例如2.0,(b = sqrt(2.0))),那么它可以正常工作.sqrt()不应该使用变量或其他东西吗?

谢谢您的帮助

Gre*_*hen 18

您需要链接数学库(在命令行上使用'-lm').在常量的情况下,编译器可能是智能的并且预先计算sqrt(2.0)(因此编译的代码基本上是'b = 1.414 ...;')


归档时间:

查看次数:

14378 次

最近记录:

11 年,6 月 前