Calculating powers with your own function - C++ Function

C++ examples for Function:Function Creation

Description

Calculating powers with your own function

Demo Code

#include <iostream>
#include <iomanip>

// Function to calculate x to the power n
double power(double x, int n)
{
  double result {1.0};
  if(n >= 0)/* w w  w. ja  va  2s  . c  o m*/
    for(int i {} ; i < n ; ++i)
      result *= x;
  else
    for(int i {} ; i < -n ; ++i)
      result /=  x;
   return result;
}

int main()
{
  // Calculate powers of 8 from -3 to +3
  for(int i {-3} ; i <= 3 ; ++i)
    std::cout << std::setw(10) << power(8.0, i);

  std::cout << std::endl;
}

Result


Related Tutorials