Write the definition of a function powerTo , which receives two parameters. The first is a double and the second is an int .
The function returns a double .
If the second parameter is negative, the function returns 0. Otherwise, it returns the value of the first parameter raised to the power of the second.
I cannot do this problem. Here's what I have:
double powerTo(double base, int power)
{
int n;
if (power %26lt; 0)
return 0;
for (double k = 1; k %26lt; n; k++)
k = base *= power;
return k;
}
This is the last problem I have to do, and it has been months and I still cannot do it!
Can anyone answer this question, using C++ and not C please
Small C++ problem, please help?
following answer is given by fred:
double powerTo(double base, int power)
{
double answer=1;
for(int i=0;i%26lt;power;i++)
answer*=base;
return answer;
}
This is perfectly alright logically, but would not server your purpose. i.e. it would not return a 0 for negative second parameter. You can modify it by introducing a statement in Fred's code as the first statement of the function:
if (power%26lt;0) return 0;
thus the function becomes:
double powerTo(double base, int power)
{
if (power%26lt;0) return 0.0;
double answer=1.0;
for(int i=0;i%26lt;power;i++)
answer*=base;
return answer;
}
Reply:Here is the correct function.
double powerTo(double base, int power)
{
double answer=1;
for(int i=0;i%26lt;power;i++)
answer*=base;
return answer;
}
How does this work?
Le'ts look at this example.
2^5
2^5 is 1 * 2 * 2 * 2 * 2 * 2. Right?
That's why the local variable "Answer" is 1 by default.
We can multiply the base as many time as power states to 1.
So you iterate from 0 to power - 1 using for loop (it means i starts from 0 and run till it reaches power) and multiply "base" to 1.
If you don't understand my answer, please add details to your questions.
*ADDED
I didn't see the answer%26lt;0 part. So the code will be...
double powerTo(double base, int power)
{
double answer=(power %26gt;=0 ? 1 : 0);
for(int i=0;i%26lt;power;i++)
answer*=base;
return answer;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment