Cpp - Write program to create a function pow(double base, int exp) to calculate integral powers of floating-point numbers.

Requirements

Write program to create a function pow(double base, int exp) to calculate integral powers of floating-point numbers.

  • Arguments: The base of type double and the exponent of type int.
  • Returns: The power base exp of type double.

For example, calling pow(2.5, 3) returns the value

2.5 * 2.5 * 2.5  =  15.625 

Demo

#include <iostream> 
#include <cmath> 
using namespace std;

double pow1(double base, int exp);

int main()     // Tests the self-defined function pow1() 
{
  double base = 0.0;
  int    exponent = 0;

  cout << "Enter test values.\n"
    << "Base (floating-point): ";  cin >> base;
  cout << "Exponent (integer):     ";  cin >> exponent;

  cout << "Result of " << base << " to the power of "
    << exponent << " = " << pow1(base, exponent)
    << endl;/*from  w w  w .j  a v a  2  s .c  o m*/

  cout << "Computing with the standard function: "
    << pow1(base, (double)exponent) << endl;
  return 0;
}
double pow1(double base, int exp)
{
  if (exp == 0)     return 1.0;
  if (base == 0.0)
    if (exp > 0)  return 0.0;
    else          return HUGE_VAL;
    if (exp < 0)
    {
      base = 1.0 / base;
      exp = -exp;
    }
    double power = 1.0;
    for (int n = 1; n <= exp; ++n)
      power *= base;
    return power;
}

Result