Search This Blog

Monday, 7 May 2018

Update raise to the power function in c++

// This program is calling a function raiseToPow.

#include <iostream>

using namespace std;

//Function declaration
double raiseToPow ( double , int );

main( )
{
double x ;
int i ;
cout << "Please enter the number" ;
cin >> x ;
cout << "Please enter the integer power that you want this  number raised to" ;
cin >> i ;

if (x==0 && i<0)
{
cout << "infinity";
}
else
{
cout << x << " raise to power " << i << " is equal to " << raiseToPow ( x , i ) ;
}

}

// function to calculate the power of some number

double raiseToPow ( double x , int power )

double result ; 
int i ; 
result = 1.0 ;
char dum;

if (x!=0)
{
if (power > 0)
  {
  for ( i = 1 ; i <= power ; i ++ )
{
result *= x ;  // same as result  = result  * x

return ( result ) ;
 
}

else

{
for ( i = -1 ; i >= power ; i -- )
{
result =result * (1/x) ;  // same as result  = result  * x


return ( result ) ;
}
}
else
{
if (power==0)
{
result=1;
return result;
}
else if (power!=0)
{
result = 0;
return result;
}
else if (power<0)
{
return 1;
}

}

}

No comments:

Post a Comment