2012-02-29 51 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