SQRT()函数不变量参数工作 [英] sqrt() function not working with variable arguments
问题描述
我不知道如果我失去了一些东西显而易见的,但现在看来,我无法计算的变量在C平方根;在SQRT()函数只似乎对常数工作。这是我的code:
I don't know if I'm missing something obvious, but it appears that I'm unable to compute square roots of a variable in C; the sqrt() function only seems to work on constants. This is my code:
#include <math.h>
#include <stdio.h>
int main()
{
double a = 2.0;
double b = sqrt(a);
printf("%f", b);
return 0;
}
当我运行这个程序,我得到以下错误:
When I run this program, I get the following error:
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.
不过,如果我有一个常数这样的替代论点的sqrt()为2.0,例如,( B =开方(2.0)
),那么它工作正常。是的sqrt()不应该用变量或什么工作?
However, if I replace the argument in sqrt() with a constant such as 2.0 for example, (b = sqrt(2.0)
), then it works fine. Is sqrt() not supposed to work with variables or something?
感谢您的帮助。
推荐答案
您需要(在命令行中使用'-lm')与数学库链接。在不断的情况下,编译器可能是聪明和precomputing的sqrt(2.0)(以便在编译code是本质上是B = 1.414 ...;')
You need to link with the math library (use a '-lm' on the command line). In the constant case, the compiler is probably being smart and precomputing sqrt(2.0) (so the code that is compiled is essentially 'b = 1.414...;')
这篇关于SQRT()函数不变量参数工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!