方法一:直接计算
```c
include
int main() {
double a, b, h;
printf("请输入立方体的底面长,底面宽及高: ");
scanf("%lf%lf%lf", &a, &b, &h);
double s = 2 * (a * b + a * h + b * h);
double v = a * b * h;
printf("立方体的表面积为: %lf, 体积为: %lf\n", s, v);
return 0;
}
```
方法二:使用函数
```c
include
float volume(float a, float b, float h) {
return a * b * h;
}
float surface_area(float a, float b, float h) {
return 2 * (a * b + a * h + b * h);
}
int main() {
float a, b, h;
printf("请输入立方体的底面长,底面宽及高: ");
scanf("%f%f%f", &a, &b, &h);
printf("立方体的表面积为: %.2f, 体积为: %.2f\n", surface_area(a, b, h), volume(a, b, h));
return 0;
}
```
方法三:使用类(适用于面向对象编程)
```c++
include using namespace std; class Cuboid { private: double length, width, height; public: Cuboid(double l, double w, double h) { length = l; width = w; height = h; } double getVolume() { return length * width * height; } double getSurfaceArea() { return 2 * (length * width + width * height + height * length); } }; int main() { double l, w, h; cout << "请输入立方体的长, 宽, 高: "; cin >> l >> w >> h; Cuboid myCuboid(l, w, h); cout << "立方体的体积为: " << myCuboid.getVolume() << endl; cout << "立方体的表面积为: " << myCuboid.getSurfaceArea() << endl; return 0; } ``` 建议 适用于简单的输入和计算,适合初学者。 将计算逻辑封装在函数中,提高了代码的可读性和可维护性。 使用面向对象编程的方法,将立方体的属性和方法封装在一个类中,适合更复杂的程序结构。 根据你的需求和编程水平,可以选择合适的方法来实现。方法一:
方法二:
方法三: