sqrt() 函数不适用于可变参数 [英] sqrt() function not working with variable arguments

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

问题描述

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

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 = sqrt(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").在常量情况下,编译器可能很聪明并且会预先计算 sqrt(2.0)(因此编译的代码本质上是 '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屋!

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