Imtiaz Raqib
Imtiaz Raqib

Reputation: 375

C - Finding Cube root of a number

In one of my assignments, I am supposed to get values of x^2, x^4 and cube root of x in which x is from 0 - 100. So far, I have this. (Testing with 5 numbers)

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

int powers(int n)
{
    return (n < 0) || (powers(n-1) && printf("%d\t%d\t%d\t\t%d\n", n, n*n, n*n*n*n, cbrt(n)));
}

int main(void)
{
    printf("number\tx^2\tx^4\t\tx^(1/3)\n");
    powers(5);

    return 0;
}

MY OUTPUT

number    x^2    x^4        x^(1/3)
0         0      0          0
1         1      1          0
2         4      16         -108170613
3         9      81         1225932534
4         16     256        -1522700739
5         25     625        -1124154156

So, my square and quatric are working as simple as it is but I cant get to work with cube root. When I do cube root separately it works. printf("Cube root of 125 is %f\n, cbrt(125)); yields Cube root of 125 is 5.0000.

I need help to why it does not work in my function. New to C programming so please be kind. (Compiler: Borland C++ and IDE: C-Free 5.0)

Upvotes: 2

Views: 1393

Answers (1)

Jack
Jack

Reputation: 133557

The problem is that cbrt accepts and returns a float or double value, which means that cbrt(n) will automatically convert n to a float/double before passing it to the function. The function will return a float/double but you are not storing it anywhere to force a conversion back to an int, you are directly passing it to printf specifying %d so the value is interpreted as an int even though it is actually a float/double.

A simple cast would be enough: (int)cbrt(n), or you could use %f or %g specifier and print it as its real type.

Also storing in a temporary variable would lead to the same conversion behavior:

int v = cbrt(n);
printf("%d\n", v);

Upvotes: 2

Related Questions