Power function returning incorrect values within the while loop

Asked

Viewed 53 times

1

I have a function power that returns the value of a potentiation receiving the parameters n and p (n^p). Outside the loop while the function returns the correct values, but within the loop function returns incorrect values, follows below the code:

double power(double, int);

int main()
{
    double n;
    int p;

    printf("%.0f\n", power(5, 2)); // aqui retorna o valor correto de 5^2

   while (1)
   {
        printf("Enter n and p (n^p): ");
        scanf("%.0f", &p);
        scanf("%d", &n);

        printf("The pow is: %.0f\n", power(n, p)); // aqui retorna valores incorretos
    }

   return 0;
}

double power(double n, int p)
{
   double pow = 1;
   int i;

for (i = 1; i <= p; i++)
    pow *= n;

   return pow;
}

1 answer

3


The main problem is the formatting of scan() wrong, and has nothing to do with the loop. d is for whole, and the double must use lf.

#include <stdio.h>

double power(double n, int p) {
    double pow = 1;
    for (int i = 1; i <= p; i++) pow *= n;
    return pow;
}

int main() {
    printf("%.0f\n", power(5, 2));
    printf("Enter n and p (n^p): ");
    double n;
    int p;
    scanf("%lf", &n);
    scanf("%d", &p);
    printf("The pow is: %.0f\n", power(n, p));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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