【问题标题】:In the C program why am I getting an error of sample.c:(.text+0xb4): undefined reference to `pow在 C 程序中,为什么我收到错误 sample.c:(.text+0xb4): undefined reference to `pow
【发布时间】:2021-07-19 19:36:59
【问题描述】:

我正在编写一个程序 C 程序来确定一个数字是否是 Armstrong 数字。 代码如下:

#include <stdio.h>
#include <math.h>
int main(){
    int inp,count,d1,d2,rem;
    float arm;
    printf("the number: ");
    scanf("%d",&inp);

    d1 = inp;
    d2 = inp;
    // for counting the number of digits
    while(d1 != 0){
        d1 /= 10; 
        ++count;
    }
    //for checking whether the number is anarmstrong number or not
    while(d2 != 0){
        rem = (d2 % 10);
        arm += pow(rem,count);
        d2 /= 10;
    }
    printf("%f",arm);
    return 0;

}

(文件名:sample.c)

我希望程序将输出显示为:

the number: 

但它显示以下错误:

usr/bin/ld: /tmp/ccleyeW0.o: in function `main':
sample.c:(.text+0xb4): undefined reference to `pow'
collect2: error: ld returned 1 exit status

我什至使用了命令 GCC -o sample sample.c -lm,但仍然出现错误。 所以我想知道是什么导致了这个错误,我该如何解决这个问题。

【问题讨论】:

  • -lm 应该已经解决了。请删除所有.o 文件,然后重试。
  • 仔细检查您使用的是-lm。缺少-lm 几乎总是导致此问题的原因。
  • float arm; -> float arm = 0;
  • 你还应该将count初始化为0

标签: c math flow-control


【解决方案1】:

如上面的 cmets 所示,您应该使用 gcc -o sample sample.c -lm 编译您的程序。 -lm 参数确保您的程序与数学库链接。

除此之外,在使用 C 中的变量之前,需要初始化变量,这不仅是一种好的风格,而且是必要的。在这种情况下,变量armcount 没有被初始化。特别是arm 的值肯定会造成麻烦,因为当您运行程序时,它将具有分配给它的内存位置(垃圾值)的任何值,这会导致不确定的行为。将两个变量都初始化为 0 应该可以修复您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    相关资源
    最近更新 更多