设计一个用于仿真自动售货机的仿真程序。在机器的初始状态建立后(即待售的物品、价格,以及初始的存货量),用户可以查看机器的当前状态,向机器投币,购买机器内的物品,得到物品和找零,假定自动售货机有3种待售物品。每种物品有四个属性:编号,物品名称,价格,数量。设计两个类(一个物品类Goods和一个机器类Machine)来实现这个仿真程序。(1)设计物品类Goods,实现物品类数据成员的赋值和获取;(2)设计Machine类,完成机器状态初始化(4分),显示目前物品状态(4分),购买物品(4分)三个功能。
时间: 2023-06-19 16:05:00 浏览: 65
基于51单片机自动售货机仿真设计(源程序+仿真文件)
5星 · 资源好评率100%
以下是一个可能的实现,其中使用了C++语言:
```c++
#include <iostream>
#include <string>
using namespace std;
class Goods {
public:
int id;
string name;
double price;
int quantity;
Goods(int id, string name, double price, int quantity) {
this->id = id;
this->name = name;
this->price = price;
this->quantity = quantity;
}
void print() {
cout << "ID: " << id << ", Name: " << name << ", Price: " << price << ", Quantity: " << quantity << endl;
}
};
class Machine {
public:
Goods* goods[3];
double balance;
Machine(Goods* g1, Goods* g2, Goods* g3) {
goods[0] = g1;
goods[1] = g2;
goods[2] = g3;
balance = 0.0;
}
void printGoods() {
cout << "Current Goods:" << endl;
for (int i = 0; i < 3; i++) {
goods[i]->print();
}
}
void buy(int id) {
if (id < 1 || id > 3) {
cout << "Invalid input. Please try again." << endl;
return;
}
Goods* g = goods[id-1];
if (g->quantity == 0) {
cout << "Sorry, the item is sold out." << endl;
return;
}
if (balance < g->price) {
cout << "Not enough balance. Please insert coins." << endl;
return;
}
balance -= g->price;
g->quantity--;
cout << "You have bought " << g->name << "." << endl;
if (balance > 0) {
cout << "Your change is " << balance << "." << endl;
balance = 0.0;
}
}
};
int main() {
Goods* g1 = new Goods(1, "Coke", 3.0, 5);
Goods* g2 = new Goods(2, "Pepsi", 2.5, 2);
Goods* g3 = new Goods(3, "Water", 1.0, 10);
Machine* m = new Machine(g1, g2, g3);
cout << "Welcome to the vending machine simulator!" << endl;
m->printGoods();
while (true) {
cout << "Please insert coins (or enter 0 to exit): ";
double coin;
cin >> coin;
if (coin == 0.0) {
break;
}
m->balance += coin;
cout << "Your current balance is " << m->balance << "." << endl;
cout << "Which item do you want to buy (1, 2, or 3)? ";
int id;
cin >> id;
m->buy(id);
m->printGoods();
}
cout << "Thank you for using the vending machine simulator!" << endl;
return 0;
}
```
该程序中,Goods类表示待售物品,包括编号、名称、价格和数量等信息。Machine类表示自动售货机,包括当前待售物品和余额等信息,实现了初始化、显示物品状态和购买物品等功能。在主函数中,首先创建三种待售物品和一个自动售货机,然后不断循环,直到用户输入0退出程序。在每次循环中,程序会提示用户插入硬币,并显示当前余额。然后程序会要求用户选择要购买的物品,并根据用户的选择调用Machine类的buy函数进行购买。购买完成后,程序会显示当前物品状态。最后,程序会输出感谢信息并结束运行。
阅读全文