题目:
要求用结构体数组,完成宠物信息登记管理。 管理宠物的名字,品种,年龄。 实现功能如下: 1. 插入宠物信息 2. 遍历宠物信息 3. 根据名字修改宠物年龄 4. 根据名字查找宠物信息
代码:
#include <stdio.h>
#include <string.h>
#define MAX_PETS 100 // 假设最多有100只宠物
#define MAX_NAME_LENGTH 50 // 假设宠物名字最长为50个字符
// 定义宠物信息的结构体
typedef struct {
char name[MAX_NAME_LENGTH];
char breed[MAX_NAME_LENGTH];
int age;
} Pet;
// 定义宠物信息数组
Pet pets[MAX_PETS];
int petCount = 0; // 当前宠物数量
// 插入宠物信息
void insertPet(const char* name, const char* breed, int age) {
if (petCount >= MAX_PETS) {
printf("宠物数量已达到上限!\n");
return;
}
strncpy(pets[petCount].name, name, MAX_NAME_LENGTH);
strncpy(pets[petCount].breed, breed, MAX_NAME_LENGTH);
pets[petCount].age = age;
petCount++;
printf("宠物信息插入成功!\n");
}
// 遍历宠物信息
void listPets() {
for (int i = 0; i < petCount; i++) {
printf("宠物名字:%s, 品种:%s, 年龄:%d\n", pets[i].name, pets[i].breed, pets[i].age);
}
}
// 根据名字修改宠物年龄
void updatePetAge(const char* name, int newAge) {
for (int i = 0; i < petCount; i++) {
if (strcmp(pets[i].name, name) == 0) {
pets[i].age = newAge;
printf("宠物年龄更新成功!\n");
return;
}
}
printf("未找到该宠物!\n");
}
// 根据名字查找宠物信息
void findPet(const char* name) {
for (int i = 0; i < petCount; i++) {
if (strcmp(pets[i].name, name) == 0) {
printf("宠物名字:%s, 品种:%s, 年龄:%d\n", pets[i].name, pets[i].breed, pets[i].age);
return;
}
}
printf("未找到该宠物!\n");
}
int main() {
// 示例用法
insertPet("狗狗", "拉布拉多", 2);
insertPet("猫咪", "英短", 1);
listPets();
updatePetAge("狗狗", 3);
findPet("猫咪");
return 0;
}
运行结果:![](https://img-blog.csdnimg.cn/direct/3afb90c05b3149898a6113c973212a53.png)