Better way of powering than this ?

I worked out a way to calculate the the result of a base to a power but is there a better way of doing it ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>


int main() {
	
	std::cout << "powering base to power" << std::endl
	          << "Enter base <space> power" << std::endl;
	double b, p;     
    std::cin >> b, p;
   	int sum = b;
    
   while(p > 0)
   {
   	sum = sum * sum;
   	p = p - 1;
   }
    
    
    std::cout << "The result is :  " << sum;
    
	return 0;
}
std::cin >> b, p;

This doesn't do what you expect. The comma operator is very confusing.

You meant to do this:

std::cin >> b >> p;

Also... your algorithm is wrong:

1
2
3
4
5
   while(p > 0)
   {
   	sum = sum * sum;
   	p = p - 1;
   }


Squaring the result (or "sum") every time does not have the desired effect.

Example.... 24=16
However with your algorithm you'll get:
1
2
3
4
5
// sum=2, p=4
sum=2*2  // sum=4, p=3
sum=4*4  // sum=16, p=2
sum=16*16  // sum=256, p=1
sum=256*256  // sum=65536, p=0 



You probably meant to do sum *= b;

Also, this will only work with integral powers. If the user inputs a power of 0.5 you'd be expected to calc the square root. Since that's not allowed here, you'd be better off making 'p' an int rather than a double.


Anyway... all that aside.... is there any reason you can't use the pow function in the <cmath> header? It already does this. Or is the assignment to do this yourself without using that header?
I didn't realise <cmath> could do this ill just use pow and go through that bit of my book again. Thank you for pointing that out.
Topic archived. No new replies allowed.