Include another header file. Call and use its function(s) in a separate file. Pr
ID: 3575572 • Letter: I
Question
Include another header file. Call and use its function(s) in a separate file.
Programming Exercise (Visual Studio, C++)
Create a main.cpp which has the main function. The main function will call your own power function that takes two numeric parameters and returns back the result of the first parameter (base) raised to the second parameter (exponent). The base could be any real numbers (meaning negative or non-negative decimal numbers) and the exponent could be any integers (meaning negative, or non-negative whole numbers).
Here are the catches that make this exercise different from previous exercises:
The power function can NOT use the already existing “pow” function from the math library. You must create your own. (hint – use a loop.)
Your own power function must NOT be located within the main file. Use separate header file and source file other than main.cpp and let main.cpp include the header file.
a screenshot of the output from your program using the following inputs
i.(2,0)
ii.(2,4)
iii.(2,-4)
iv.(0.1,2)
v.(-0.1,-4)
Explanation / Answer
//power.h
//prototype for power function
double power(double base, int exp);
//power.cpp
/*definition for power function
*input : real number base and integer type exp
*it returns power of a number to given exponent*/
double power(double base, int exp)
{
double prod = 1;
int abs_exp = 0;
//if exponet is negetive we need to divide instead of multiplying
if (exp < 0)
abs_exp = exp * -1;
else
abs_exp = exp;
for (int i = 0; i < abs_exp; i++)
{
if (exp < 0)
prod /= base;
else
prod *= base;
}
return prod;
}
//main.cpp
#include<iostream>
#include"power.h"
using namespace std;
int main()
{
//test power function with different values
cout << "i.(2,0) = "<<power(2, 0) << endl;
cout << "ii.(2,4) = " << power(2,4) << endl;
cout << "iii.(2,-4) = " << power(2, -4) << endl;
cout << "iv.(0.1,2) = " << power(0.1, 2) << endl;
cout << "v.(-0.1,-4) = " << power(-0.1, -4) << endl;
cout << "vi.(-0.1,-3) = " << power(-0.1, -3) << endl;
return 0;
}
------------------------------------------------------------------------------------------------------------------------
output:
i.(2,0) = 1
ii.(2,4) = 16
iii.(2,-4) = 0.0625
iv.(0.1,2) = 0.01
v.(-0.1,-4) = 10000
vi.(-0.1,-3) = -1000