225k views
0 votes
Write a C function, unsigned int power(unsigned int x, unsigned int p), that calculates xp. Place the function in a file with a filename hw3_prob3-5.c. Include a main function that calls this function with several values to test the function. Be sure to handle the case of p = 0.

1 Answer

4 votes

Answer:

unsigned int power(unsigned int x, unsigned int p)

{

unsigned int answer = 1;

while(p--)

{

answer *= x;

}

return answer;

}

void Test(unsigned x, unsigned int p, unsigned int expected)

{

int answer = power(x, p);

std::cout << x << "^" << p << "=" << answer;

if (answer == expected)

{

std::cout << " (as expected)" << std::endl;

}

else

{

std::cout << " ERROR" << std::endl;

}

}

int main()

{

Test(3, 0, 1);

Test(3, 1, 3);

Test(3, 2, 9);

}

Step-by-step explanation:

In case of questions, dm me!

User Orberkov
by
5.4k points