0

Whenever i write 5 as n and p as 2 ,i get the output as 24...please let me know what's wrong? for other numbers it is completely fine.

#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;

int main()
{
    double n, p;
    cout << "enter the number" <<endl;
    cin >> n;
    cout << "enter the power" <<endl;
    cin >> p;
    int result = pow(n, p);
    cout << "Result is " << result;
    return 0;
}
Dovahkiin
  • 946
  • 14
  • 25
  • 3
    `pow` returns a double, probably `24.999999999....`, which will be `24` when you save it in an `int`, but I cannot reproduce: http://ideone.com/jPgljt – mch Jul 03 '17 at 14:18
  • 1
    Detailed answer at https://stackoverflow.com/a/25678721/3701834 – aniliitb10 Jul 03 '17 at 14:33

1 Answers1

0

You have problems with your data types!

double n, p; // here you use double types
std::cout << "enter the number" << std::endl;
std::cin >> n;
std::cout << "enter the power" << std::endl;
std::cin >> p;
int result = pow(n, p); // then here you use double pow(double, double) but assign it to an int
std::cout << "Result is " << std::result;

Solution:

double result = pow(n, p);
Adam
  • 115
  • 3
  • 9
  • It doesn't solve the problem. If the parameters of power is double, you could still face the similar issue and won't get exact power. – aniliitb10 Jul 03 '17 at 15:02
  • @aniliitb10 If you mean that numerical algorithms don't give you the exact value of a real number (they are rounding off the value), that's true, but that's a fact, too. – Adam Jul 03 '17 at 15:11