实践项目名称:编程实现超市购物!
实验要求:
构建和实现三个情景:
1)在家,确定出门门购物之前携带金额数目;
2)在超市,对购买的商品选择和商品数目的选择(利用数组实现);
3)交易付款,系统提示交易金额的剩余,若金额不够给与用户提示。
控制台输出那种:
#include <stdio.h>
#include <stdlib.h>
int main() {
int choice, amount, total = 0, price;
int products[5] = {0}; // 记录每个商品的数量,初始化为0
int prices[5] = {10, 8, 6, 5, 3}; // 商品的单价
// 情景1:在家确定出门前携带的金额数目
printf("请输入你携带的金额数目:");
scanf("%d", &amount);
printf("你携带了%d元钱。\n", amount);
// 情景2:在超市选择商品和商品数量
while (1) {
printf("请选择要购买的商品:\n");
printf("1. 鸡腿 10元/个\n");
printf("2. 牛奶 8元/瓶\n");
printf("3. 面包 6元/个\n");
printf("4. 鸡翅 5元/个\n");
printf("5. 饮料 3元/瓶\n");
printf("6. 结束购物\n");
scanf("%d", &choice);
if (choice == 6) {
break;
}
if (choice < 1 || choice > 5) {
printf("无效选择,请重新输入!\n");
continue;
}
printf("请输入%d的数量:", choice);
int num;
scanf("%d", &num);
if (num < 0) {
printf("数量不能为负数,请重新输入!\n");
continue;
}
price = prices[choice-1] * num;
if (total + price > amount) {
printf("金额不足,购买失败!\n");
continue;
}
products[choice-1] += num; // 更新每个商品的数量
total += price; // 更新购物总金额
}
// 情景3:交易付款
printf("你购买的商品如下:\n");
for (int i = 0; i < 5; i++) {
if (products[i] > 0) {
printf("%d. %d个 %d元\n", i+1, products[i], products[i]*prices[i]);
}
}
printf("总共 %d元\n", total);
if (total == amount) {
printf("你付款成功,谢谢惠顾!\n");
} else if (total < amount) {
printf("你付款成功,找零 %d元,谢谢惠顾!\n", amount-total);
} else {
printf("金额不足,交易失败!\n");
}
return 0;
}
我可以提供以下关于编程实现超市购物场景的建议:
首先需要确定用户在家预算的金额数目,可以通过以下代码实现:
double budget = 0;
printf("请输入您的预算金额:\n");
scanf("%lf", &budget);
在超市购物可以定义一个商品结构体,包含商品名称和价格等属性:
typedef struct {
char name[20];
double price;
int count;
} Good;
在程序中,可以构建一个商品数组,以实现对购买商品的选择和增加:
int goodCount; // 商品总数
Good goods[10]; // 商品数组,最多10个元素
int i;
for (i = 0; i < goodCount; i++) {
printf("请输入第%d个商品名称:\n", i+1);
scanf("%s", goods[i].name);
printf("请输入第%d个商品价格:\n", i+1);
scanf("%lf", &(goods[i].price));
printf("请输入第%d个商品数量:\n", i+1);
scanf("%d", &(goods[i].count));
}
在付款环节,需要统计购物金额和用户剩余金额比较,并给出相应信息:
double total = 0.0; // 购物总金额
int i;
for (i = 0; i < goodCount; i++) {
total += goods[i].price * goods[i].count;
}
printf("购物总金额:%lf\n", total);
if (total > budget) {
printf("您的余额不足,请及时充值!\n");
} else {
printf("交易成功,剩余金额:%lf\n", budget - total);
}
这些代码只是一个思路示例,具体实现方式可能会因项目要求和环境而异。