在 C 中,当幂设置为 1/2 时,为什么幂函数 return 1?

In C why does the power function return 1 when the power is set to 1/2?

当我使用以下代码时,我试图复制 sqrt(x) 某物等于 X^(1/2)

的想法
pow(x, (1/2);

不管我输入什么值,它都返回1。我已经用 sqrt 函数解决了这个问题,但想知道为什么以后会发生这种情况。

在它的原始形式中,1/2 是整数除法,产生的结果是 0

数学 101:任何提高 0 的都是 1。

整数除法得到整数结果,因此 1/2 得到 0,而不是 0.5。至少有一个操作数需要是浮点值才能得到浮点结果,比如1 / 2.0。尽管您可以只写 0.5 并避免胃灼热。

1(整数文字)除以 2(整数文字)要求 整数除法(在运算符 / 上)结果 0。从那时起,您将 0 赋给函数 pow(3),它将您的 0 转换为 0.0(作为函数所需的 double)和这就是您正在计算的 x0.0 次方,即 1.0.

你用过吗

pow(x, (1.0/2.0)); /* there's a closing parenthesis missing in your sample code */

使用浮点文字,而不是整数,除法应该是浮点数,你得到 0.5 作为结果,你应该计算 x.[=28= 的平方根]

顺便说一句,你有一个函数 sqrt(3) 可以计算平方根,在同一个库中:

pru.c

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

/* ... */

int main()
{

    double x = 625.0;

    printf("square root of %.10f is %.10f\n", x, sqrt(x));
    printf("%.10f to the power 1/2 is %.10f\n", x, pow(x, 1.0/2.0));
    return 0;
}

执行该代码得到:

$ make pru
cc -O2 -Wno-error  -Werror    -o pru pru.c 
$ pru
square root of 625.0000000000 is 25.0000000000
625.0000000000 to the power 1/2 is 25.0000000000
$ _

1/2 在 C++ 中是 0,因为两者都是整数。你可以使用 1.0/2.0 或 0.5 做你想做的事。