【问题标题】:pow function in CC中的pow函数
【发布时间】:2012-06-02 04:51:51
【问题描述】:

我编写了一个具有来自 math.h 库的幂函数的 C 代码。当我编译我的程序时,我收到一个错误“未定义对‘pow’函数的引用”,我使用 gcc 编译器(fedora 9)编译我的程序。

然后我在gcc中插入-lm标志,错误被省略但pow函数的输出为0。

#include<math.h>
main()
{
double a = 4, b = 2;
b = pow(b,a);
}

谁能帮助我?我的编译器有问题吗??

谢谢。

【问题讨论】:

  • 错误省略但输出为0 什么输出?你没有打印任何东西。
  • @cnicutar - 也许 OP 是指pow()返回值
  • 我使用 printf("%d\n", b);打印值。
  • 这是包含错误的 printf 行。确保发布所有代码。

标签: c gcc pow math.h


【解决方案1】:

对于所有寻求此类答案的人:

这不起作用

gcc my_program.c -o my_program

它会产生这样的东西:

/tmp/cc8li91s.o: In function `main':
my_program.c:(.text+0x2d): undefined reference to `pow'
collect2: ld returned 1 exit status

这会起作用

gcc my_program.c -o my_program -lm

【讨论】:

  • 这已经在问题本身中说明了。 (以及在 Stack Overflow 上的许多其他 Q 和 As 中。)
【解决方案2】:

这里有关于基数和指数的混淆。这不是很明显,因为 2^4 和 4^2 都等于 16。

void powQuestion()
{
    double a, b, c;

    a = 4.0;
    b = 2.0;
    c = pow(b, a);

    printf("%g ^ %g = %g\n", a,b,c);        // Output: 4 ^ 2 = 16

    a = 9.0;
    b = 2.0;
    c = pow(b, a);

    printf("%g ^ %g = %g\n", a,b,c);        // Output: 9 ^ 2 = 512  >> Wrong result; 512 should be 81 <<


    // K & R, Second Edition, Fifty Second Printing, p 251: pow(x,y) x to the y

    double x, y, p;

    x = 9.0;
    y = 2.0;
    p = pow(x, y);

    printf("%g ^ %g = %g\n", x, y, p);      // Output: 9 ^ 2 = 81


    // even more explicitly

    double base, exponent, power;

    base = 9.0;
    exponent = 2.0;
    power = pow(base, exponent);

    printf("%g ^ %g = %g\n", base, exponent, power);    // Output: 9 ^ 2 = 81
}

【讨论】:

    【解决方案3】:

    您缺少将值打印到标准输出的 printf 行。 试试这个:

    #include <stdio.h>
    #include <math.h>
    
    int main() {
            double a=4, b=2, c;
    
            c = pow(b,a);
            printf("%g^%g=%g\n", a,b,c);
            return 0;
    }
    

    输出将是:

    4^2=16
    

    【讨论】:

      【解决方案4】:

      你的程序没有输出任何东西。

      您所指的 0 可能是退出代码,如果您没有从 main 显式返回,它将是 0。

      尝试将其更改为符合标准的签名并返回b

      int main(void) {
        ...
        return b;
      }
      

      请注意,返回值基本上限制为 8 位的信息,非常非常有限。

      使用printf 显示值。

      #include <stdio.h>
      ...
        printf("%f\n", b);
      ...
      

      必须使用浮点转换说明符(fge)来打印 double 值。您不能使用 d 或其他人并期望一致的输出。 (这实际上是未定义的行为。)

      【讨论】:

      • 好答案。我的猜测是 OP 使用了错误的 printf 说明符。
      • 我使用 printf 来显示 b 值。 b 的值为 0。我使用 %d 说明符。
      • 如果你像我上面所说的那样使用 printf,你会看到16.0000...%d 用于整数类型。
      • @cnicutar:你的水晶球很强。
      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2018-09-08
      • 1970-01-01
      • 2012-05-15
      相关资源
      最近更新 更多