c - 为什么 sqrt 函数不适用于通过用户输入获取的值?

标签 c sqrt

以下代码:

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

int main(void)
{
    long long int a;
    scanf("%lld", &a);
    printf("%lf", sqrt(a));
    return 0;
}

给出输出:

source_file.c: In function ‘main’:
source_file.c:9:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%lld", &a);
     ^
/tmp/ccWNm2Vs.o: In function `main':
source.c:(.text.startup+0x65): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

但是,如果我执行 long long int a = 25; 并删除 scanf 语句,或者只是执行 sqrt(25),它们都有效(正确给出输出 5.000000)。

我检查了this question , 但它适用于 C++ 并使用函数重载,而 afaict C 没有函数重载(这就是为什么我们有 sqrtfsqrtsqrtl如果我没记错的话)。此外,无论我采用 long long int 还是 double 类型的 a,上述代码都会失败。所以,这些问题可能不相关。
另外,关于其他 linked question ,对于不断定义的值,我没有发生错误,而恰好是链接问题的情况。

那是什么原因呢?为什么常量值适用于 sqrt,而可变用户输入值却不行?

最佳答案

就像评论中提到的那样,您没有链接到 libm,因此 sqrt 在链接时未定义。

Why would a constant value work for sqrt, while a variable user input value won't?

因为 GCC 将 sqrt 识别为 builtin function并且能够在编译时计算编译时常量的平方根,并完全放弃对 sqrt 的调用,从而避免后续的链接器错误。

The ISO C90 functions ... sqrt, ... are all recognized as built-in functions unless -fno-builtin is specified (or -fno-builtin-function is specified for an individual function).

如果您要添加 -fno-builtin-sqrt,无论您将什么传递给 sqrt,您都会看到链接器错误。

关于c - 为什么 sqrt 函数不适用于通过用户输入获取的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53028549/

相关文章:

c - ifconfig 和套接字 inet_ntop 的不同 IP 结果

在c中使用sqrt()编译错误

julia - 如何在 Julia 中执行向量的逐元素平方根?

haskell - haskell中的苍鹭方法

c - 在终端中使用 C 时,哈希符号注释掉代码

c - 对于作业,我必须比较两个日期,使用 C 中的结构。我不确定我的逻辑是否错误

c++ - "Enlarging"一个二维数组 (m,n)

c - 陷入位图的实现中

c++ - 使用while循环确定数字的平方根c++

algorithm - 如何计算和存储 sqrt(n) 最多 10^6 位小数的数字?