用结构体实现简单的个人小金库信息管理。每个人都可以建立自己的小金库,在里面存放自己的资金。购物时会花费资金,这是支出;获得奖学金、爸妈寄的生活费或打工赚的工钱等,这是收入。小金库的资金会不断地变化,可以开发 管理系统对小金库进行管理。要求从键盘输入至少3笔记录,并显示。
时间: 2024-03-12 18:45:34 浏览: 23
好的,以下是一个简单的结构体实现的个人小金库信息管理程序:
```c
#include <stdio.h>
#define MAX_RECORDS 100 // 最多记录100笔
struct Record {
char type; // 类型,'i'表示收入,'o'表示支出
float amount; // 金额
char description[100]; // 描述
};
struct Wallet {
char name[100]; // 名称
float balance; // 余额
struct Record records[MAX_RECORDS]; // 记录
int count; // 记录数
};
void add_record(struct Wallet *wallet, char type, float amount, char *description) {
// 添加一笔记录
if (wallet->count < MAX_RECORDS) {
struct Record *record = &(wallet->records[wallet->count]);
record->type = type;
record->amount = amount;
strncpy(record->description, description, sizeof(record->description));
wallet->count++;
if (type == 'i') {
wallet->balance += amount;
} else {
wallet->balance -= amount;
}
} else {
printf("记录已满,无法添加!\n");
}
}
void print_records(struct Wallet *wallet) {
// 打印所有记录
printf("记录总数:%d\n", wallet->count);
for (int i = 0; i < wallet->count; i++) {
struct Record *record = &(wallet->records[i]);
printf("%c %.2f %s\n", record->type, record->amount, record->description);
}
}
int main() {
struct Wallet wallet;
printf("请输入小金库名称:");
scanf("%s", wallet.name);
wallet.balance = 0;
wallet.count = 0;
while (1) {
printf("请输入记录类型(i表示收入,o表示支出):");
char type;
scanf(" %c", &type); // 注意加上空格,避免上一个输入留下的回车影响
if (type != 'i' && type != 'o') {
printf("无效的类型!\n");
continue;
}
printf("请输入金额:");
float amount;
scanf("%f", &amount);
printf("请输入描述:");
char description[100];
scanf("%s", description);
add_record(&wallet, type, amount, description);
print_records(&wallet);
printf("当前余额:%.2f\n", wallet.balance);
printf("是否继续输入(y/n):");
char choice;
scanf(" %c", &choice);
if (choice != 'y' && choice != 'Y') {
break;
}
}
printf("感谢使用个人小金库管理系统!\n");
return 0;
}
```
这个程序中,结构体`Record`表示一条记录,包括类型、金额和描述;结构体`Wallet`表示一个小金库,包括名称、余额、记录和记录数。我们提供了两个函数`add_record`和`print_records`,分别用于添加记录和打印所有记录。在`main`函数中,我们首先输入小金库的名称,然后循环读取用户输入的记录,并通过上述两个函数进行处理。最后输出感谢信息,程序结束。