C语言习题~day39

简介: C语言习题~day39


1.

思路:

1. 首先定义了一个基类 Shape,但它实际上主要是作为派生类的基础部分,这里只是包含坐标信息,实际未作具体使用。

2. 定义了 Rectangle 矩形类,包含长和宽等属性,以及计算矩形面积的函数 getRectangleArea。

3. 定义了 Circle 圆类,包含半径属性和计算圆面积的函数 getCircleArea。

4. 定义了 Square 正方形类,它是从 Rectangle 类派生的,继承了矩形类的属性和方法,然后专门定义了计算正方形面积的函数 getSquareArea。

5. 在 main 函数中,分别输入矩形的长和宽、圆的半径、正方形的边长,然后调用相应的面积计算函数来计算并输出它们的面积。

#include <stdio.h>
 
// 基类 shape
typedef struct {
    int x;
    int y;
} Shape;
 
// 矩形类
typedef struct {
    Shape base;
    int length;
    int width;
} Rectangle;
 
// 计算矩形面积
int getRectangleArea(Rectangle rect) {
    return rect.length * rect.width;
}
 
// 圆类
typedef struct {
    Shape base;
    double radius;
} Circle;
 
// 计算圆面积
double getCircleArea(Circle circle) {
    return 3.14 * circle.radius * circle.radius;
}
 
// 正方形类,从矩形类派生
typedef struct {
    Rectangle base;
} Square;
 
// 计算正方形面积
int getSquareArea(Square square) {
    return square.base.length * square.base.length;
}
 
int main() {
    Rectangle rect;
    Circle circle;
    Square square;
 
    scanf("%d %d", &rect.length, &rect.width);  // 修改这里,先输入长和宽
    scanf("%lf", &circle.radius);
    scanf("%d", &square.base.length);
 
    printf("%d\n", getRectangleArea(rect));
    printf("%g\n", getCircleArea(circle));
    printf("%d\n", getSquareArea(square));
 
    return 0;
}


目录
相关文章
TU^
|
8天前
|
存储 C语言
C语言习题~day35
C语言习题~day35
TU^
11 1
TU^
|
8天前
|
编译器 C语言
C语言习题~day31
C语言习题~day31
TU^
8 2
TU^
|
8天前
|
算法 程序员 C语言
C语言习题~day36
C语言习题~day36
TU^
14 1
TU^
|
8天前
|
存储 C语言
C语言习题~day34
C语言习题~day34
TU^
8 1
TU^
|
8天前
|
算法 C语言
C语言习题~day33
C语言习题~day33
TU^
8 1
TU^
|
8天前
|
C语言
C语言习题~day32
C语言习题~day32
TU^
8 1
TU^
|
8天前
|
C语言
C语言习题~day30
C语言习题~day30
TU^
7 1
TU^
|
8天前
|
自然语言处理 C语言 C++
C语言习题~day29
C语言习题~day29
TU^
7 1
TU^
|
8天前
|
存储 C语言
C语言习题~day28
C语言习题~day28
TU^
7 1
TU^
|
8天前
|
C语言
C语言习题~day27
C语言习题~day27
TU^
8 1