Construct an overloaded function equivalent to the pow(x, n), where x can be either integer or float and n is an integer.
Aug 31, 2018For this question, there will be two argument function. The function is overloaded based on the type of arguments, and is float and integer.
Program:
#include<iostream> using namespace std; // do not include cmath header for this //program as it may conflict // declarations of overloaded functions int pow(int x, int n); float pow(float x, int n); int main(){ int a = 10; float b = 20.5; int index = 5; cout<<"pow("<<a<<", "<<index<<") = "<<pow(a, index)<<endl; cout<<"pow("<<b<<", "<<index<<") = "<<pow(b, index)<<endl; return 0; } // function defination int pow(int x, int n){ // using simple mechanism for repeated multiplication int product = x; for(int i = 0; i < n - 1; i++){ product *= x; } return product; } float pow(float x, int n){ float product = x; for(int i = 0; i < n - 1; i++){ product *= x; } return product; }
Sample Run:
pow(10, 5) = 100000 pow(20.5, 5) = 3.62051e+06