Ask your own question, for FREE!
Computer Science 15 Online
OpenStudy (anonymous):

(c++ question) ....Write a function "power" that receives two input parameters x and n. The function should calculate and return x^n. Write a program to call and test the function power

OpenStudy (anonymous):

What are you having trouble with?

OpenStudy (anonymous):

do you know how to define a function?

OpenStudy (anonymous):

that's the problem , I don't know how to define the function. can you help me please?

OpenStudy (anonymous):

First, a function in C-like languages must have a header that includes: return_type name(var_type var_name1, var_type var_name2...) and must be enclosed in curly braces. So, it will have the form: int power(int x, int n) { } Now, how do you raise a number to a given power n? You multiply it n times, correct? So the code will be: int power(int x, int n) { int temp = 1; while (n > 0) { temp *= x; n--; } return temp; } Surely, there are fancier ways to code it, I just tried to be very explicit. Hope this helps, mate :-)

OpenStudy (anonymous):

I totally get it , that was very helpful . it was way better than reading all those complicated long pages in the book and get bored eventually . thank you so much , really appreciate your help.

OpenStudy (anonymous):

i'm trying to debug it ,but there seems to be a problem .

OpenStudy (anonymous):

what is the problem

OpenStudy (anonymous):

its not running , there seem to be an error in the code above when i try to run it on the microsoft visiual studio, can anyone help me please?

OpenStudy (anonymous):

what's the error message?

OpenStudy (anonymous):

(the code looks correct to me)

OpenStudy (anonymous):

This code compiles and runs fine on my Visual Studio 2008 express edition (created new Win32 console project): // power.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "stdio.h" int power(int x, int n) { int temp = 1; while (n > 0) { temp *= x; n--; } return temp; } int _tmain(int argc, _TCHAR* argv[]) { int p = power(3,2); printf("%d\n", p); return 0; }

OpenStudy (anonymous):

did u get the right answer to your question or not ?

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!