2012-02-29 48 views
0

我有一个项目,我必须做以下;MATLAB收据打印随机值问题

你有一个小企业,你卖6种不同的产品。选择你的产品 和他们的价格范围在20p到25.00英镑(这可能是完全虚构的)。您的 店有4名员工,其中一人将在购买时到达。 您的任务是编写MATLAB代码准备虚假交易收据,如下面的 解释。 有一个客户在到达。他们想要购买3种随机产品,每种产品的具体数量为 。例如,顾客需要2个卡布奇诺,1个羊角面包和6个覆盆子 松饼。 (1)从列表中随机选择3种产品。对于每种产品,请在1和9之间选择一个随机数 。 (2)计算总成本。 (3)随机选择工作人员完成交易。 (4)假设价格包含20%的增值税。计算包含在价格中的增值税金额。 (6)在MATLAB命令窗口中将收据准备为文本。使用当前日期和时间 (检查datestr(now,0))。 您的代码应以图片中显示的格式输出收据。应该有 60个符号。选择我们自己的商店名称。

receipt example.

到目前为止我的代码如下:

clear all 
clc 
close all 

items = {'apples ','carrots ','tomatoes','lemons ','potatoes','kiwis '};% products 
price = {3.10, 1.70, 4.00, 1.65, 9.32, 5.28};% item prices. I set spaces for each entry  in order to maintain the border format. 
employee = {'James','Karina','George','Stacey'};%the employees array 
disp(sprintf('+-----------------------------------------------+')); 

disp(sprintf('|\t%s \t\t\tAlex''s Shop |\n|\t\t\t\t\t\t\t\t\t\t\t\t|',  datestr(now,0))); 

totalPrice = 0; 
for i = 1:3 
    randItems = items {ceil(rand*6)}; 
    randprice = price {ceil(rand*6)}; 
    randQuantity = ceil(rand*9);% random quantity from 1 to 9 pieces 
    randEmployee = employee{ceil(rand*4)}; 
    itemTotal = randprice * randQuantity;%total price of individual item 
    totalPrice = totalPrice + itemTotal; 

    disp(sprintf('|\t%s\t (%d) x %.2f = £ %.2f \t\t\t|', randItems, randQuantity, randprice, itemTotal)) 

end 

disp(sprintf('|\t\t\t\t-----------------------------\t|')); 

disp(sprintf('|\t\t\t\t\t\t\t\t\t\t\t\t|\n|\t Total to pay \t £  %.2f\t\t\t\t|',totalPrice)); 

disp(sprintf('|\t VAT \t\t\t\t £ %.2f\t\t\t\t| \n|\t\t\t\t\t\t\t\t\t\t\t\t|',  totalPrice*0.2)); 

disp(sprintf('|\tThank you! You have been served by %s\t|\t', randEmployee)); 

disp(sprintf('+-----------------------------------------------+')); 

我的课程的问题如下。从物品清单中选择一个随机物品后,我会选择随机分配的价格。我不想要这个。我希望找到一种方法,可以在生成要添加到购物篮中的随机商品时自动为每个要打印的商品分配预设价格。我希望这个解释对你来说已经足够了,如果你有任何问题可以随意问。先谢谢你。

回答

1

当编写

randItems = items {ceil(rand*6)}; 
randprice = price {ceil(rand*6)}; 

你计算随机索引到阵列items,然后计算随机索引到阵列price。如果您改为将您通过ceil(rand*6)计算的指数分配给一个单独的变量, index,您可以重新使用它从itemsprice中挑选物品#3。因此,第i个项目将始终以第i个价格出现。

+0

所以我会做点像 index = ceil(rand * 6); 然后把它放在randItems和randPrice的大括号中? – 2012-02-29 12:57:26

+1

@AlexEncoreTr:就是这样。 – Jonas 2012-02-29 13:01:27

+0

非常感谢。它不能更明显!我不知道为什么我这么长时间被卡住了。 – 2012-02-29 13:03:09