Square and cube of the same variable in C

Asked

Viewed 144 times

0

Good guys, I have a question. My teacher was teaching functions in C and asked us to do a function with a variable that calculates the square and cube and prints the two.

My code so far has remained so, but it can only return one, or square or cube.

#include <stdio.h>
#include <stdlib.h>

// Assinatura da função (DECLARAÇÃO)
int fSoma(int *valor1);

int main(void) {
    int numero[1], numero2, resultado[1], valor1, x;

    printf("Digite um numero aleatorio"); 
    scanf("%d", &numero[1]);

    for (x=0; x<2; x++){

    resultado[x] = fSoma ( &numero[1] );

    printf("%d \n", resultado[x]);

}
}

    int fSoma(int *valor1){
    int mult[1], x;
    for (x=0; x<2; x++){

    mult[0] = pow(*valor1, 2);
    mult[1] = pow(*valor1, 3);


    return mult[x];

}


}
  • Did your teacher ask you for the same function that calculates the square and the cube, or did he ask for a function that calculates the square and a function that calculates the cube? Also, you can already use struct?

  • A single function, I can use anything, so that I can read in a single function, the cube and the square

  • Rethink your logic according to the semantics of commands. When you do return[x] it exits the function and returns to the caller. No use putting the returnwithin a loop, at the first call it will terminate the function. Note also that when you declare mult[1]is reserving memory for 1 int, like, it seems to me, you want memory to 2 ints would need to declare: int mult[2] and the possible indices would be 0 and 1.

1 answer

0


I see you’re using pointers, but in the wrong way. One possibility would be to use a function like this:

void quadrado_cubo(int valor, int *quadrado, int *cubo) {
    *quadrado = valor * valor;
    *cubo = valor * valor * valor;
}

And then you call with it:

int numero, quadrado, cubo;
scanf("%d", &numero);
quadrado_cubo(numero, &quadrado, &cubo);
  • I tried using yours, I couldn’t either

  • And type, there in the square void(int value, int *square, int *cube) it wants a value only, for example void square(int value)

  • @Joãomarcelotavares The function has to return the values or it just has to show them with printf?

Browser other questions tagged

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