0

How to calculate a number with power as decimal number without using pow() function.

Here is the code to calculate the power as decimal number using pow() function.

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
  double num,exp;
  cin>>num>>exp;// number and the power of it
  cout<<"Power  is: "<<pow(num,exp)<<endl;
}

Input: 2 2.5
Output:
Power is: 5.65685

But the another method without using the pow() function is given below (Improvement is accepted.)

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
  double num,exp;
   cin>>num>>exp;
   double temp = 0;
  for(int i=0;i<exp;i++)
  {
    temp+=num;
  }
  cout<<"Power is: "<<temp<<endl;
   return 0;
}

Input: 2 2.5
Output:
Power is: 4 (incorrect)

Finally I want to find out the power of base number (Power can be decimal value) manually without using pow() function. Thanks in advance!!.

user2736738
  • 30,591
  • 5
  • 42
  • 56
susan097
  • 3,500
  • 1
  • 23
  • 30
  • 1
    Every behavior is right. – user2736738 Feb 17 '18 at 12:07
  • 1
    Think about the comparison of the ***integer*** variable `i` to the ***floating point*** variable `exp` in your loop condition. – Some programmer dude Feb 17 '18 at 12:09
  • 1
    Since when does __`+`__ constitute exponentiation???? – Paul Ogilvie Feb 17 '18 at 12:10
  • 1
    I also try the comparison of int variable `i` to the floating point variable `exp` but not works. I also edit this – susan097 Feb 17 '18 at 13:54
  • Hint: convert your variables to the same type (integer or floating point) before comparing. I don't think you want the compiler to do this for you. – Thomas Matthews Feb 17 '18 at 18:26
  • @Sushant Your code has several issues, one of which is the `+=` which should be `*=` (remember: exponentiation is equivalent to repeated multiplication, just the same as multiplication is repeated addition). Also, it simply is not possible to compute pow(a,b) for an arbitrary (non-integer) b just by repeatedly multiplying by a, since the fractional part means that we need some more complex computations. See the questions that this was marked a duplicate of to find an overview of different approaches (using log/exp, Taylor series, ...) to compute pow(a,b) for general a and b. – Tobias Ribizel Feb 17 '18 at 19:20

0 Answers0