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

Viewed 385

When I use the following code I tried to replicate the idea that sqrt(x) of something equals X^(1/2)

pow(x, (1/2);

It returned 1 no matter what value I entered. I already solved this issue with the sqrt function but wanted to know why this is happening for the future.

4 Answers

In it's original form, 1/2 is integer division, producing a result of 0.

Math 101: Anything raised 0, is 1.

1 (integer literal) divided by 2 (integer literal) asks for integer division (on the operator /) which results in 0. From that on, you are giving 0 to a function, pow(3), that converts your 0 into 0.0 (as a double required by the function) and this is what you are calculating, x to the power of 0.0 which is 1.0.

Had you used

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

using floating point literals, instead of integer, the division should have been floating point, you got 0.5 as result and you should be calculating the square root of x.

By the way, you have a function sqrt(3) to do square roots, in the same library:

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;
}

Executing that code gives:

$ 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
$ _

Integer division yields an integer result, so 1/2 yields 0, not 0.5. At least one of the operands needs to be a floating point value to get a floating point result, such as 1 / 2.0. Although you can just write 0.5 and save the heartburn.

1/2 in c++ is 0 since both are integers. You can use 1.0/2.0 or 0.5 to do what you want.

Related