-5

Write a function to compute the power an, where n ≥ 0. It should have the following specification and prototype:

Sets *p to the n’th power of a and returns 0, except when n < 0 or p is NULL, in which case it returns -1.

int power(int a, int n, int * p);'

So far, I am here:

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

int power(int a, int n, int *p);
  if ( n < 0 || p == NULL)
return -1;

Should I use a for loop? Or does that not make any sense at all? I don't know how to calculate an any other way than a * a ... * a.

4

1 回答 1

0

是的,使用 for 循环。我不清楚您想如何处理错误条件(p 为 null 或 n < 0)。无论如何,在本例中,变量“res”都会被覆盖。

#include <stdio.h>

int power(int a, int n, int *p)
{
        int i;

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

        return p == NULL || n < 0 ? -1 : 0;
}

int main()
{
        int res;

        power(4, 2, &res);
        printf("%d\n", res);

        return 0;
}
于 2013-09-14T04:03:29.007 回答