I'm basically trying to rewrite math.pow, I have the following obviously I'm not getting the concept of returning values. What exactly am I doing wrong?
public static int power(int x, int n)
{
if (n == 0) return 1;
int i,total;
for(i = 0; i < n-1 ;i++);
{
total = (x * total);
}
return total;
}
You need to initialize total to 1.
int total = 1;
You can just rewrite everything to:
public static int power(int x, int n)
{
int total = 1;
for(int i = 0; i < n; i++) // i can be declared here directly
{
total = (x * total);
}
return total; // total remains 1 if n = 0
}
public static int power(int x, int n)
{
int total = 1; // Initialized total to 1
for(int i = 0; i < n; i++)
{
total = x*total;
}
return total;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With