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.
Instructor's notes: You cannot use the pow() function since you are essentially writing a simpler version of the pow() function. Also, don't forget to take into account when the second parameter is passed the value 0.
And this is what I got so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
double powerTo(double x, int y)
{
if(y < 0)
{
return 0;
}
else
{
for(int i = 1; i <= y; i++)
{
double value = x;
value *= x;
}
}
}
So my question is, how can I write a function that functions the same as a value raised to the power other than using pow()?
move some code around, fairly simple to get from where you are to where you need to be, first you need to actually return something, what do you have to return (prodding question, should be fairly obvious)
The code is flawed. The for loop will calculate value = x*x a total of y times (value is reinitialized to x every iteration). Move line 11 to follow line 8.
The suggestions above should help you with your problem, but I believe a simpler way you could have set this up would be through using recursion. You could set up your coding as:
1 2 3 4 5 6 7 8 9
double powerTo(double x, int y)
{
if( y < 1)
return 1;
else
{
return x * (powerTo(x, y-1));
}
}
This is a lot cleaner and takes up less space. It also makes setting up your for loop a little easier. Don't forget that if your initial y-value is 0, your return value should be 1; (and value to the 0 power is equal to 1).