Search code examples
cfunctionsubroutine

Create a function that return the pow b^e


I have to create a function that return the value of b^e. This is what I have done:

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

int funzione_potenza (int b, int e);

int main ()
{
    int b, e, potenza;

    printf("Inserisci la base: ");
    scanf("%d",&b);

    printf("Inserisci l'esponente: ");
    scanf("%d",&e);

    printf("La potenza e' %d",potenza);

    return 0;
}

int funzione_potenza (int b, int e)
{
    int potenza;

    potenza = pow(b,e);

    return potenza;
}

When i run it, it displays a false value of the power (ex. 5343123) What is wrong?


Solution

  • There are two issues:

    First of all you're getting a garbage value because you never call the funzione_potenza function.

    int main()
    {
      int b, e, potenza;
    
      printf("Inserisci la base: ");
      scanf("%d", &b);
    
      printf("Inserisci l'esponente: ");
      scanf("%d", &e);
    
      potenza = funzione_potenza(b, e);       // <<<<<<<<<< insert this line
    
      printf("La potenza e' %d", potenza);
    
      return 0;
    }
    

    Secondly you don't even need the funzione_potenza which is just a wrapper around pow, you can call pow directly:

    ...
    scanf("%d", &e);
    
    potenza = pow(b, e);
    
    printf("La potenza e' %d", potenza);
    ...