#include <iostream> #include <cmath> using namespace std; class figure { protected: double He; double Wi; public: figure(double H, double W); }; figure::figure(double H, double W) { cin >> W >> H; cout << W << " ### " << H << endl; He = H; Wi = W; } class rectangle :public figure { public: rectangle(double H, double W) :figure(H, W) { }; void area(); void display(); }; void rectangle::display() { cout << "W: " << Wi << "H: " << He << endl; } void rectangle::area() { cout << "S= " << Wi * He << endl; } class triangle :public figure { public: triangle(double H, double W) :figure(H, W) { }; void area(); void display(); }; void triangle::display() { cout << "W: " << Wi << "H: " << He << endl; } void triangle::area() { double n = 0.5; cout << n * Wi * He << endl; } int main() { double width, height; cin >> width >> height; triangle tri(width, height); rectangle rect(width, height); tri.display(); cout << ". The area is "; cout << tri.area() << endl; rect.display(); cout << ". The area is " << rect.area() << endl; return 0; }
时间: 2024-03-22 21:37:09 浏览: 173
#include_iostream.h_
4星 · 用户满意度95%
这段代码中存在一些问题。具体问题如下:
1. `#include` 库文件时应该每个文件一行,而不是写在同一行。
2. 类 `figure` 的构造函数中的输入语句应该放在 `main` 函数中,而不是在构造函数中。
3. 类 `triangle` 和类 `rectangle` 中的 `area` 函数应该返回一个值,而不是 `void` 类型。
4. 在 `main` 函数中,输出 `tri.area()` 和 `rect.area()` 的语句应该分别放在 `tri.area()` 和 `rect.area()` 的函数调用后面。
下面是修改后的代码:
```
#include <iostream>
#include <cmath>
using namespace std;
class figure {
protected:
double He;
double Wi;
public:
figure(double H, double W) : He(H), Wi(W) {}
};
class rectangle : public figure {
public:
rectangle(double H, double W) : figure(H, W) {}
double area();
void display();
};
void rectangle::display() {
cout << "W: " << Wi << "H: " << He << endl;
}
double rectangle::area() {
return Wi * He;
}
class triangle : public figure {
public:
triangle(double H, double W) : figure(H, W) {}
double area();
void display();
};
void triangle::display() {
cout << "W: " << Wi << "H: " << He << endl;
}
double triangle::area() {
double n = 0.5;
return n * Wi * He;
}
int main() {
double width, height;
cin >> width >> height;
triangle tri(height, width);
rectangle rect(height, width);
tri.display();
cout << ". The area is " << tri.area() << endl;
rect.display();
cout << ". The area is " << rect.area() << endl;
return 0;
}
```
阅读全文