用c++编写一个求x的次幂的程序,需要用到函数
时间: 2023-05-15 16:07:42 浏览: 104
可以使用 pow 函数来求 x 的次幂,代码如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x, n;
cout << "请输入底数 x 和指数 n:" << endl;
cin >> x >> n;
double result = pow(x, n);
cout << x << " 的 " << n << " 次幂为:" << result << endl;
return 0;
}
```
其中,pow 函数的原型为:
```c++
double pow(double x, double y);
```
它的作用是求 x 的 y 次幂。
相关问题
用C++编写一个函数,实现数组中元素逆序,要求用到指针
可以这样实现: void reverseArray(int *a, int len) {
int *left = a;
int *right = a + len - 1;
while (left < right) {
int temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
用c++编写一个矩形类,已知两点求面积和周长
好的,我知道了。这里是用 C 语言编写的一个简单的矩形类,可以根据两点来计算矩形的面积和周长:
```c
#include <stdio.h>
#include <math.h>
struct point {
float x;
float y;
};
struct rectangle {
struct point pt1;
struct point pt2;
};
float distance(struct point a, struct point b) {
float dx = a.x - b.x;
float dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
float perimeter(struct rectangle rect) {
float width = distance(rect.pt1, rect.pt2);
float height = distance((struct point){rect.pt1.x, rect.pt2.y}, (struct point){rect.pt2.x, rect.pt1.y});
return 2 * (width + height);
}
float area(struct rectangle rect) {
float width = distance(rect.pt1, rect.pt2);
float height = distance((struct point){rect.pt1.x, rect.pt2.y}, (struct point){rect.pt2.x, rect.pt1.y});
return width * height;
}
int main() {
struct rectangle rect = {{0,0},{2,2}};
printf("The perimeter of the rectangle is %f\n", perimeter(rect));
printf("The area of the rectangle is %f\n", area(rect));
return 0;
}
```
在这个示例中,我们首先定义了一个 `point` 结构体来表示二维平面上的一个点,然后定义了一个 `rectangle` 结构体来表示一个由两个点确定的矩形。接下来我们实现了一个 `distance` 函数来计算两个点之间的距离,这个函数用到了勾股定理。最后我们定义了 `perimeter` 和 `area` 函数来分别计算矩形的周长和面积,这里用到了上面定义的 `distance` 函数。
在 `main` 函数中,我们定义了一个矩形 `rect`,并且输出了它的周长和面积。
希望这个示例能够帮助你理解如何用 C 语言编写简单的矩形类!