编写求幂函数,能够计算X",其中X可以是整型量、长整型和双精度型效值,k为 正整数。要求使用以下两种方法分别编写两个程序: (1)函数重载。 (2)函数模板。
时间: 2023-05-20 22:07:25 浏览: 39
答案:
1. 函数重载程序:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int power(int x, int k) {
int res = 1;
while (k--) {
res *= x;
}
return res;
}
long power(long x, int k) {
long res = 1;
while (k--) {
res *= x;
}
return res;
}
double power(double x, int k) {
double res = 1;
while (k--) {
res *= x;
}
return res;
}
int main() {
int a = 2;
long b = 3;
double c = 1.5;
int k = 4;
cout << power(a, k) << endl;
cout << power(b, k) << endl;
cout << power(c, k) << endl;
return 0;
}
```
2. 函数模板程序:
```c++
#include <iostream>
#include <cmath>
using namespace std;
template<typename T>
T power(T x, int k) {
T res = 1;
while (k--) {
res *= x;
}
return res;
}
int main() {
int a = 2;
long b = 3;
double c = 1.5;
int k = 4;
cout << power(a, k) << endl;
cout << power(b, k) << endl;
cout << power(c, k) << endl;
return 0;
}
```
注意:这两种方法都可以计算整型量、长整型和双精度型效值的幂,使用方法也都相同,直接调用即可。