自己写的:
#include<iostream>
//编写一个求x的n次方的函数
using std::cout;
using std::cin;
using std::endl;
double power(double x,int n);
void main(){
double x;
int n;
cout <<"请输入底数:"<<endl;
cin>>x;
cout <<"请输入指数"<<endl;
cin>>n;
cout <<x<<"的"<<n<<"次方为:"<<power(x,n)<<endl;
}
double power(double x,int n){
double s=1;
for(int i=0; i<n; ++i){
s*=x;
}
return s;
}
课本的:
#include<iostream>
using namespace std;
//计算x的n次方
double power(double x, int n){
double val = 1.0;
while(n--){
val*=x;
}
return val;
}
int main(){
cout <<"5 to the power 2 is "<<power(5,2)<<endl;
return 0;
}