Q:

Write a C++ program to calculate x raised to the power n (xn)

0

Write a C++ program to calculate x raised to the power n (xn)

Sample Input: x = 7.0
n = 2
Sample Output: 49

Sample Output:

7^2 = 49

3^9 = 19683

6.2^3 = 238.328

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>
using namespace std;

double powxn(double x, int n) {
        if (n < 0){
            x = 1 / x;
            n = -n;
        }
         
        double result = 1;
        for (auto i = 0; i < n; ++i)
        {
            result = result * x;
        }

        return result;
    }

int main(void)
{
    double x = 7.0;
    int n = 2;
    cout << "\n" << x << "^" << n << " = " << powxn(x, n) << endl; 
    x = 3;
    n = 9;
    cout << "\n" << x << "^" << n << " = " << powxn(x, n) << endl;     
    x = 6.2;
    n = 3;
    cout << "\n" << x << "^" << n << " = " << powxn(x, n) << endl;         
    return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now