de <stdio.h>
include <string.h>
define MAX_PRODUCTS 100
typedef struct {
char name[100];
float price;
int quantity;
} Product;
Product products[] = {
{"牛奶", 3.0, 0},
{"面包", 2.0, 0},
{"方便面", 5.0, 0},
{"矿泉水", 1.5, 0},
{"火腿肠", 5.0, 0},
{"溜溜梅", 5.0, 0},
{"薄荷糖", 10.0, 0},
{"豆腐干", 1.0, 0},
{"辣条", 0.5, 0},
{"纸巾", 1.0, 0}
};
int product_count = 10;
float get_price(const char* name) {
for (int i = 0; i < product_count; i++) {
if (strcmp(products[i].name, name) == 0) {
return products[i].price;
}
}
return -1;
}
void add_product() {
if (product_count < MAX_PRODUCTS) {
printf("请输入商品名称:");
scanf("%99s", products[product_count].name);
printf("请输入商品价格:");
scanf("%f", &products[product_count].price);
products[product_count].quantity = 0;
product_count++;
} else {
printf("商品数量已达上限。\n");
}
}
void buy_product(const char* name, int quantity) {
for (int i = 0; i < product_count; i++) {
if (strcmp(products[i].name, name) == 0) {
products[i].quantity += quantity;
return;
}
}
if (product_count < MAX_PRODUCTS) {
strcpy(products[product_count].name, name);
products[product_count].price = get_price(name); products[product_count].quantity = quantity;
product_count++;
} else {
printf("商品数量已达上限。\n");
}
}
void print_receipt() {
printf("小票如下:\n商品名\t单价\t数量\t总价\n");
float total = 0;
int printed[MAX_PRODUCTS] = {0};
for (int i = 0; i < product_count; i++) {
if (products[i].quantity > 0 && printed[i] == 0) {
printf("%s\t%.2f\t%d\t%.2f\n", products[i].name, products[i].price, products[i].quantity, products[i].price * products[i].quantity);
total += products[i].price * products[i].quantity;
printed[i] = 1;
}
}
printf("总价\t%.2f\n", total);
}
int main() {
char command[10];
char product_name[100];
int quantity;
while (1) {
printf("请输入指令(buy, add, receipt, exit):");
printf("牛奶 3元\n");
printf("面包 2元\n");
printf("方便面 5元\n");
printf("矿泉水 1元\n");
printf("火腿肠 1.5元\n");
printf("溜溜梅 5元\n");
printf("薄荷糖 10元\n");
printf("辣条 0.5元\n");
printf("纸巾 1元\n");
scanf("%s", command);
if (strcmp(command, "buy") == 0) {
printf("请输入商品名称和数量:");
scanf("%99s %d", product_name, &quantity);
buy_product(product_name, quantity);
} else if (strcmp(command, "add") == 0) {
add_product();
} else if (strcmp(command, "receipt") == 0) {
print_receipt();
} else if (strcmp(command, "exit") == 0) {
break;
} else {
printf("未知指令。\n");
}
}
return 0;
}