(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
What are you having trouble with?
do you know how to define a function?
that's the problem , I don't know how to define the function. can you help me please?
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 :-)
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.
i'm trying to debug it ,but there seems to be a problem .
what is the problem
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?
what's the error message?
(the code looks correct to me)
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; }
did u get the right answer to your question or not ?
Join our real-time social learning platform and learn together with your friends!