Answer to Question #210579 in C++ for qqqq

Question #210579

Raising a number n to a power p is the same as multiplying n by itself p times. Write a function called power() that takes a double value for n and an int value for p, and returns the result as a double value. Use a default argument of 2 for p, so that if this argument is omitted, the number n will be squared. Write a main() function that gets values from the user to test this function.


1
Expert's answer
2021-06-25T05:22:09-0400
#include <iostream> 




using namespace std;


//a function called power() that takes a double value for n and an int value for p, and 
//returns the result as a double value. Use a default argument of 2 for p, so that if 
//this argument is omitted, the number n will be squared.
double power(double n,int p=2){
	double result=1;
	for(int i=0;i<p;i++){
		result*=n;
	}
	return result;
}


int main (){
	double n;
	int p;
	double result=0;
	//Write a main() function that gets values from the user to test this function.
	cout<<"Enter n: ";
	cin>>n;
	cout<<"Enter p: ";
	cin>>p;
	if(p<0){
		result=power(n);
		cout<<n<<"^2 = "<<result<<"\n\n";
	}else{
		result=power(n,p);
		cout<<n<<"^"<<p<<" = "<<result<<"\n\n";
	}
	


	system("pause");
	return 0;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS