Bootstrap

C 结构体基础练习题

这些题目都是我自己练过挑选出来的,有错误请指出哦谢谢🪻


🔹定义一个名为“Student”的结构体,其中包含成员的name(姓名)、age(年龄)和totalMarks(总分)。编写一个 C 程序来输入两个学生的数据,显示他们的信息,并找到总分的平均值。 

#include <stdio.h> 

struct Student {
    char name[50];
    int age;
    float totalMarks;
};

int main() {
    // Declare variables to store information for two students 声明2个变量来储存信息
    struct Student student1, student2;

    // Input data for the first student 输入第一个学生的数据
    printf("Input details for Student 1:\n");
    printf("Name: ");
    scanf("%s", student1.name); 
    printf("Age: ");
    scanf("%d", &student1.age);
    printf("Total Marks: ");
    scanf("%f", &student1.totalMarks);

    // Input data for the second student 输入第二个学生的数据
    printf("\nInput details for Student 2:\n");
    printf("Name: ");
    scanf("%s", student2.name);
    printf("Age: ");
    scanf("%d", &student2.age);
    printf("Total Marks: ");
    scanf("%f", &student2.totalMarks);

    // Display information for both students 输入第三个学生的数据
    printf("\nStudent 1 Information:\n");
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("Total Marks: %.2f\n", student1.totalMarks);

    printf("\nStudent 2 Information:\n");
    printf("Name: %s\n", student2.name);
    printf("Age: %d\n", student2.age);
    printf("Total Marks: %.2f\n", student2.totalMarks);

    // Calculate and display the average total marks 计算并显示平均分
    float averageMarks = (student1.totalMarks + student2.totalMarks) / 2;
    printf("\nAverage Total Marks: %.2f\n", averageMarks);

    return 0;
}

🔹定义一个名为 Time 的结构体,其中包含hours(小时)、minutes(分钟) 和 seconds(秒)。编写一个 C 程序,输入两个时间,将它们相加,并以适当的时间格式显示结果。

#include <stdio.h>

// Define the structure "Time" 定义结构体
struct Time {
    int hours;
    int minutes;
    int seconds;
};

int main() {
    // Declare variables to store two times and the result 声明变量来储存2个时间和1个结果
    struct Time time1, time2, result;

    // Input time1 输入第一个时间
    printf("Input the first time (hours minutes seconds): ");
    scanf("%d %d %d", &time1.hours, &time1.minutes, &time1.seconds);

    // Input time2 输入第二个时间
    printf("Input the second time (hours minutes seconds): ");
    scanf("%d %d %d", &time2.hours, &time2.minutes, &time2.seconds);

    // Add the two times 输入第三个时间
    result.seconds = time1.seconds + time2.seconds;
    result.minutes = time1.minutes + time2.minutes + result.seconds / 60;
    result.hours = time1.hours + time2.hours + result.minutes / 60;

    // Adjust minutes and seconds 调整分钟和秒
    result.minutes %= 60;
    result.seconds %= 60;

    // Display the result 显示结果
    printf("\nResultant Time: %02d:%02d:%02d\n", result.hours, result.minutes, result.seconds);

    return 0;
}

🔹定义一个名为 Book 的结构体,其中包含title(标题)、author(作者)和price(价格)。编写一个 C 程序来输入三本书的详细信息,找出最贵和价格最低的书籍,并显示它们的信息。

#include <stdio.h>
#include <float.h> // Include for FLT_MAX and FLT_MIN constants

// Define the structure "Book" 定义结构体
struct Book {
    char title[100];
    char author[100];
    float price;
};

int main() {
    // Declare variables to store details for three books 声明变量来储存3本书本的数据
    struct Book book1, book2, book3;

    // Input details for the first book 输入第一本书的数据
    printf("Input details for Book 1:\n");
    printf("Title: ");
    scanf("%s", book1.title); 
    printf("Author: ");
    scanf("%s", book1.author); 
    printf("Price: ");
    scanf("%f", &book1.price);

    // Input details for the second book 输入第二本书的数据
    printf("\nInput details for Book 2:\n");
    printf("Title: ");
    scanf("%s", book2.title);
    printf("Author: ");
    scanf("%s", book2.author);
    printf("Price: ");
    scanf("%f", &book2.price);

    // Input details for the third book 输入第三本书的数据
    printf("\nInput details for Book 3:\n");
    printf("Title: ");
    scanf("%s", book3.title);
    printf("Author: ");
    scanf("%s", book3.author);
    printf("Price: ");
    scanf("%f", &book3.price);

    // Find the most expensive book 找到最贵的书
    struct Book mostExpensive;
    if (book1.price >= book2.price && book1.price >= book3.price) {
        mostExpensive = book1;
    } else if (book2.price >= book1.price && book2.price >= book3.price) {
        mostExpensive = book2;
    } else {
        mostExpensive = book3;
    }

    // Find the lowest priced book 找到最便宜的书
    struct Book lowestPriced;
    if (book1.price <= book2.price && book1.price <= book3.price) {
        lowestPriced = book1;
    } else if (book2.price <= book1.price && book2.price <= book3.price) {
        lowestPriced = book2;
    } else {
        lowestPriced = book3;
    }

    // Display information for the most expensive book 显示最贵的书的数据
    printf("\nMost Expensive Book:\n");
    printf("Title: %s\n", mostExpensive.title);
    printf("Author: %s\n", mostExpensive.author);
    printf("Price: %.2f\n", mostExpensive.price);

    // Display information for the lowest priced book 显示最便宜的书的数据
    printf("\nLowest Priced Book:\n");
    printf("Title: %s\n", lowestPriced.title);
    printf("Author: %s\n", lowestPriced.author);
    printf("Price: %.2f\n", lowestPriced.price);

    return 0;
}

🔹一个名为Queue(队列)的结构体,包含MAX_SIZE(最大尺寸),front(前索引),rear(后索引)。该队列符合先进先出原则:元素从后面添加,从前面移除。

Q1 :定义该结构体;

Q2 :编写一个名为initializeQueue函数,将队列设置为空状态(索引均为-1);

Q3 :编写两个函数:

  • int isEmpty(struct Queue *queue)
    如果队列为空则返回 1,否则返回 0。

  • int isFull(struct Queue *queue)
    如果队列已满(循环),则返回 1,否则返回 0。

Q4 :编写void enqueue(struct Queue *queue, int value)函数要求添加一个元素到队尾;

Q5 :编写int dequeue(struct Queue *queue)函数要求从队列前面移除一个元素;

Q6 :main()运行;

#include <stdio.h>
#define MAX_SIZE 100

// Define the structure "Queue" 定义结构体
struct Queue {
    int arr[MAX_SIZE];
    int front, rear;
};

// Function to initialize the queue 初始化队列函数
void initializeQueue(struct Queue *queue) {
    queue->front = -1;
    queue->rear = -1;
}

// Function to check if the queue is empty 检查队列是否为空的函数
int isEmpty(struct Queue *queue) {
    return (queue->front == -1 && queue->rear == -1);
}

// Function to check if the queue is full 检查队列是否为满的函数
int isFull(struct Queue *queue) {
    return (queue->rear == MAX_SIZE - 1);
}

// Function to enqueue an element into the queue 添加元素的函数
void enqueue(struct Queue *queue, int value) {
    if (isFull(queue)) {
        printf("Queue is full. Cannot enqueue.\n");
        return;
    }

    if (isEmpty(queue)) {
        // If the queue is empty, set front and rear to 0 如果队列为空,将前后索引设为零
        queue->front = 0;
        queue->rear = 0;
    } else {
        queue->rear = (queue->rear + 1) % MAX_SIZE;
    }

    // Enqueue the value 添加元素
    queue->arr[queue->rear] = value;
    printf("Enqueued: %d\n", value);
}

// Function to dequeue an element from the queue 移除元素的函数
int dequeue(struct Queue *queue) {
    int value;

    if (isEmpty(queue)) {
        printf("Queue is empty. Cannot dequeue.\n");
        return -1; 
    }

    // Dequeue the value 移除元素
    value = queue->arr[queue->front];

    if (queue->front == queue->rear) {
        // If the queue has only one element, set front and rear to -1 如果队列只有一个元素,将前后索引设为负一
        queue->front = -1;
        queue->rear = -1;
    } else {
        queue->front = (queue->front + 1) % MAX_SIZE;
    }

    printf("Dequeued: %d\n", value);
    return value;
}

int main() {
    // Declare and initialize a queue 声明并初始化队列
    struct Queue myQueue;
    initializeQueue(&myQueue);

    // Enqueue some elements 添加元素
    enqueue(&myQueue, 100);
    enqueue(&myQueue, 200);
    enqueue(&myQueue, 300);

    // Dequeue elements 移除元素
    dequeue(&myQueue);
    dequeue(&myQueue);

    return 0;
}

🔹定义一个名为 Complex 的结构体,包含real(实部)和imag(虚部)。编写一个 C 程序来对两个复数进行加法和乘法。

#include <stdio.h>

// Define the structure "Complex" 定义结构体
struct Complex {
    float real;
    float imag;
};

// Function to add two complex numbers 两个复数相加的函数
struct Complex addComplex(struct Complex num1, struct Complex num2) {
    struct Complex result;
    result.real = num1.real + num2.real;
    result.imag = num1.imag + num2.imag;
    return result;
}

// Function to multiply two complex numbers 两个复数相乘的函数
struct Complex multiplyComplex(struct Complex num1, struct Complex num2) {
    struct Complex result;
    result.real = (num1.real * num2.real) - (num1.imag * num2.imag);
    result.imag = (num1.real * num2.imag) + (num1.imag * num2.real);
    return result;
}

// Function to display a complex number 显示复数
void displayComplex(struct Complex num) {
    printf("%.2f + %.2fi\n", num.real, num.imag);
}

int main() {
    // Declare variables to store two complex numbers 声明2个变量储存复数
    struct Complex complexNum1, complexNum2, sumResult, productResult;

    // Input details for the first complex number 输入第一个复数数据
    printf("Input details for Complex Number 1 (real imag): ");
    scanf("%f %f", &complexNum1.real, &complexNum1.imag);

    // Input details for the second complex number 输入第二个复数数据
    printf("Input details for Complex Number 2 (real imag): ");
    scanf("%f %f", &complexNum2.real, &complexNum2.imag);

    // Add the two complex numbers 相加
    sumResult = addComplex(complexNum1, complexNum2);

    // Multiply the two complex numbers 相乘
    productResult = multiplyComplex(complexNum1, complexNum2);

    // Display the results 显示结果
    printf("\nSum of Complex Numbers:\n");
    displayComplex(sumResult);

    printf("\nProduct of Complex Numbers:\n");
    displayComplex(productResult);

    return 0;
}

🔹定义一个名为Car的结构体,包含carID(汽车 ID)、model(车型)和rentalRatePerDay(每日租赁费率)等信息。编写一个 C 程序来输入三辆汽车的数据,计算指定天数的总租赁费用,并显示结果。

#include <stdio.h>

// Define the structure "Car" 定义结构体
struct Car {
    int carID;
    char model[50];
    float rentalRatePerDay;
};

// Function to calculate the total rental cost for a specified number of days 计算租凭金额的函数
float calculateRentalCost(struct Car car, int days) {
    return car.rentalRatePerDay * days;
}

int main() {
    // Declare variables to store details for three cars 声明3个变量储存汽车数据
    struct Car car1, car2, car3;
    int rentalDays;

    // Input details for the first car 输入第一个汽车数据
    printf("Input details for Car 1:\n");
    printf("Car ID: ");
    scanf("%d", &car1.carID);
    printf("Model: ");
    scanf("%s", car1.model); 
    printf("Rental Rate per Day: ");
    scanf("%f", &car1.rentalRatePerDay);

    // Input details for the second car 输入第二个汽车数据
    printf("\nInput details for Car 2:\n");
    printf("Car ID: ");
    scanf("%d", &car2.carID);
    printf("Model: ");
    scanf("%s", car2.model);
    printf("Rental Rate per Day: ");
    scanf("%f", &car2.rentalRatePerDay);

    // Input details for the third car 输入第三个汽车数据
    printf("\nInput details for Car 3:\n");
    printf("Car ID: ");
    scanf("%d", &car3.carID);
    printf("Model: ");
    scanf("%s", car3.model);
    printf("Rental Rate per Day: ");
    scanf("%f", &car3.rentalRatePerDay);

    // Input the number of rental days 输入租凭时长
    printf("\nEnter the number of rental days: ");
    scanf("%d", &rentalDays);

    // Calculate and display the total rental cost for each car 输出租凭金额
    printf("\nTotal Rental Cost for Car 1: %.2f\n", calculateRentalCost(car1, rentalDays));
    printf("Total Rental Cost for Car 2: %.2f\n", calculateRentalCost(car2, rentalDays));
    printf("Total Rental Cost for Car 3: %.2f\n", calculateRentalCost(car3, rentalDays));

    return 0;
}

;