Calculation of cubic root in vectors

Asked

Viewed 398 times

1

Hello! I am doing an exercise where it is necessary to calculate the cubic root of 10 numbers stored in a vector and transfer them from vector A (where the numbers were read) to vector B ( where they will be transformed into the cube of A, but this is done in another function). the problem is that my program is not doing this conversion. I tried to add a third variable C but it did not help The code is this:

#include <stdio.h>
#include <math.h>
#define tam 10

void cubo(int *B);

int main(){
    int A[tam], B[tam];

    for(int i = 0; i < tam; i++){
        scanf("%d", &A[i]);
    }
    cubo(A);
    return 0;
}
void cubo(int *B){
  long C[tam];
    for(int i = 0; i < tam; i++){
        C[i] = sqrt(sqrt(B[i]));
        printf("%d\n", B[i]);
    }
}
  • Mathematically I don’t think that the square root of the square root is the cube root of a number. Maybe you can use pow(B[i], 1.0/3.0) and print not the parameter but the result of the operation.

1 answer

1


If you want the cubic root, it’s no use doing sqrt(sqrt(numero)), for the square root of the square root is the fourth root.

There is no function ready for the cubic root, but we know that the root N of a number is the same as that number raised to 1 / N, so you can use pow(numero, 1.0 / 3.0) to calculate.

The problem is that the cube root will not necessarily be an integer, so I suggest changing the type of b for float. Also, if you want to play the numbers of a for b, then both would have to be function parameters (besides the amount of items, which I think is better to be a parameter than to depend on the constant - in that case it wouldn’t make a difference, but in a more general function, I would do so):

#define TAM 10

void raizCubica(int*a, float *b, int qtd){
    for(int i = 0; i < qtd; i++){
        b[i] = pow(a[i], 1.0 / 3.0);
    }
}

int main() {
    int a[TAM];
    float b[TAM];

    for(int i = 0; i < TAM; i++){
        scanf("%d", &a[i]);
    }
    raizCubica(a, b, TAM);

    for(int i = 0; i < TAM; i++){
        printf("%.5f\n", b[i]); // imprimir com 5 casas decimais
    }
    return 0;
}

I also changed the name of the function, since cube is not the same as cube root. And I did the function only save the values in b (the printing can be done later, the function only calculates and stores in the array - and I did so also to show that the values were of facts placed in b).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.