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

  • برمجة سي بلس بلس
  • برمجة

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

الأجوبة

#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;
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...