English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have to write a program that calulates and returns the value of x^n.

Is this code correct:

#include

double PowerOf (double x, int n)
{
for(i = 0; i<= n; i++)
result = x;
result = result * x;
return (result);
} // end function

2006-11-05 12:23:25 · 5 answers · asked by Anonymous in Computers & Internet Programming & Design

5 answers

Short answer, no. Inside your loop you keep resetting the result variable back to x. You won't get what you need.

Plus, you need a main function if this program is going to compile, right? Use cin to get the x and n variables from the user and cout to output the result. Also, don't forget

using namespace std;

But as for the actual power function, it should look something like this.

double PowerOf(double x, int n)
{
double result = 1;
for (int i = 0; i < n; i++)
{
result *= x;
}
return result;
}

However, I believe if you #include you can just use the pow function to do all the work for you.

2006-11-05 12:30:57 · answer #1 · answered by Anonymous · 2 0

The program is worng, and will output only (X^2) irrespective of value of n. For that you have to take statement result = x, out of for loop. Even after that it will fail as it will always return (x ^ (n+1)). For this you have to start the loop from 1 and not from n. Also you have to change result = 1, instead of result = x.

For the recursive program, it will fail, because of end condintion. It should (if n == 0) return 1;
and function wont go recursively for using n - 1; as it only important what value you are passing to the parameter, instead of changing this value.

correct recursive program is

double PowerOf(double x, int n)
{
if(n == 0) return 1;
else return (x*PowerOf(x,n-1));
}

non-recursive funcyion will be

#include

double PowerOf (double x, int n)
{

if (n == 0) return 1;
if (n == 1) return x;
double result = x;
for(i = 2; i<= n; i++)
result = result *x;
return result;
} // end function

2006-11-06 03:06:29 · answer #2 · answered by manoj Ransing 3 · 0 0

Most of the other posts have been fairly accurate. The last one, by Origamix is clever, but in the last statement, he needs an n-- rather than n-1. As written, the recursive function would continue endlessly.

2006-11-05 21:21:08 · answer #3 · answered by Deirdre H 7 · 0 1

looks good, try this, it recursive.

double power(double x, int n)
{
if(n = 0)
{return x * x;}
else
{
return (x * power(x, n-1));
}
}

i think thats correct, havent tested it.

2006-11-05 20:35:05 · answer #4 · answered by origamix60 3 · 0 0

why not use the power operator
power(result,n);

2006-11-05 20:33:50 · answer #5 · answered by Dead 4 · 0 0

fedest.com, questions and answers