C语言结构体与动态内存应用

C语言结构体与动态内存实践

253、定义结构体类型 coord ,其成员为点的坐标(例如 x y )。定义结构体类型 rectangle ,其成员为两个 coord 类型的结构体(例如 point_A point_B )。编写一个函数,该函数以矩形对角线的两个端点作为参数,每个端点应为 coord 类型的结构体。该函数应计算并返回矩形的面积。编写一个程序,使用 rectangle 类型读取矩形对角线的坐标,并使用该函数显示其面积。

#include <stdio.h>

struct coord {
    double x;
    double y;
};

struct rectangle {
    struct coord point_A; /* 第一个对角点 */
    struct coord point_B; /* 第二个对角点 */
};

double rect_area(struct coord *c1, struct coord *c2); 

int main(void){
    struct rectangle rect;
    printf("Enter the x and y coords of the first point: ");
    scanf("%lf%lf", &rect.point_A.x, &rect.point_A.y);
    printf("Enter the x and y coords of the second point: ");
    scanf("%lf%lf", &rect.point_B.x, &rect.point_B.y);
    printf("Area: %f\n", rect_area(&rect.point_A, &rect.point_B));
    return 0;
}

double rect_area(struct coord *c1, struct coord *c2){
    double base, height;
    if(c1->x > c2->x)
        base = c1->x - c2->x;
    else
        base = c2->x - c1->x;
    if(c1->y > c2->y)
        height = c1->y - c2->y;
    else
        height = c2->y - c1->y;
    return base*height; /* 返回面积 */
}

254、定义一个名为pixel的结构体类型,它有三个名为red、green和blue的整数成员。编写一个程序,创建一个二维图像(例如3×5),其元素是pixel类型的结构体。用[0, 255]范围内的随机值初始化每个结构体的成员。然后,程序应显示原始图像,将图像向右旋转90°,并显示旋转后的图像(例如5×3)。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 3
#define COLS 5

struct pixel /* RGB格式 (红 - 绿 - 蓝) */ {
    unsigned char red;   /* 值在 [0, 255] 范围内 */
    unsigned char green;
    unsigned char blue;
};

void rotate_right_90(struct pixel img[][COLS], struct pixel tmp[][ROWS]);

int main(void) {
    int i, j;
    struct pixel img[ROWS][COLS], tmp[COLS][ROWS];

    srand(time(NULL)); /* 创建随机颜色 */
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            img[i][j].red = rand() % 256;
            img[i][j].green = rand() % 256;
            img[i][j].blue = rand() % 256;
        }
    }

    printf("*** 原始图像 ***\n\n");
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("(%d, %d, %d) ", img[i][j].red, img[i][j].green, img[i][j].blue);
        }
        printf("\n");
    }

    rotate_right_90(img, tmp);

    printf("\n*** 旋转后的图像 ***\n\n");
    for (i = 0; i < COLS; i++) {
        for (j = 0; j < ROWS; j++) {
            printf("(
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值