C语言模拟商场会员积分兑换: 结构体类型定义如下: struct member{ char name[20]; char num[20]; int total; struct member *next; }; 要求实现如下功能: (1)建立链表:自定义函数建立单链表来存放会员的信息,如果输入大写‘Y’字符则继续创建结点存储会员信息,否则按任意键结束输入。 (2)积分兑换:自定义函数按照编号查找会员,并为这个会员兑换积分,5000分兑换10元,输入要兑换的积分数,输出兑换了多少元和剩余积分。如果没有找到,输出此会员不存在。 (3)写自定义函数释放链表所占内存。 (在主函数依次调用各函数即可) 输入输出如下: **创建节点提示:"请依次输入每个会员的编号、姓名、积分: \n" **输入节点数据格式:"%s %s %d" **是否继续创建提示:"是否继续输入,按Y键继续输入,其他键就结束.\n" **输入提示:"请输入要兑换积分的会员编号:\n" **输入格式:"%s" 如果没找到,输出"此会员不存在.\n" 找到了,完成兑换 **输入提示:"5000分兑换10元,你想兑换多少积分?\n" **输入格式:"%d" **输出格式:"你兑换了%d元,剩余积分为:%d\n"
时间: 2023-12-10 20:37:44 浏览: 96
下面是一个可能的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct member{
char name[20];
char num[20];
int total;
struct member *next;
};
struct member *create_list();
void exchange_points(struct member *head);
void free_list(struct member *head);
int main()
{
struct member *head = create_list();
exchange_points(head);
free_list(head);
return 0;
}
struct member *create_list()
{
struct member *head = NULL, *tail = NULL;
char input[20];
do {
printf("请依次输入每个会员的编号、姓名、积分:\n");
struct member *new_node = (struct member *)malloc(sizeof(struct member));
scanf("%s %s %d", new_node->num, new_node->name, &new_node->total);
new_node->next = NULL;
if (head == NULL) {
head = new_node;
} else {
tail->next = new_node;
}
tail = new_node;
printf("是否继续输入,按Y键继续输入,其他键就结束.\n");
scanf("%s", input);
} while (input[0] == 'Y');
return head;
}
void exchange_points(struct member *head)
{
char num[20];
printf("请输入要兑换积分的会员编号:\n");
scanf("%s", num);
struct member *current = head;
while (current != NULL && strcmp(current->num, num) != 0) {
current = current->next;
}
if (current == NULL) {
printf("此会员不存在.\n");
} else {
int points;
printf("5000分兑换10元,你想兑换多少积分?\n");
scanf("%d", &points);
if (points <= current->total) {
int exchanged = points / 5000 * 10;
current->total -= points;
printf("你兑换了%d元,剩余积分为:%d\n", exchanged, current->total);
} else {
printf("积分不足无法兑换.\n");
}
}
}
void free_list(struct member *head)
{
while (head != NULL) {
struct member *next = head->next;
free(head);
head = next;
}
}
```
注意,上面的实现没有对输入做错误处理,例如输入的积分数为负数或者非数字字符,这些情况应该根据实际需要进行处理。
阅读全文