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("(