Why doesn't my code loop back up to the top again and how to fix it
조회 수: 1 (최근 30일)
이전 댓글 표시
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/226204/image.png)
(This is the photo of my text)
%% Cash register
NumItems = 0;
Answer = 1; % Assuming there is at least 1 item
while Answer == 1
Answer = input('Is there a new item? hit 1 for yes 0 for no: ','s'); % altering final condition
ItemNum = input('What is the 5 digit item number: '); % getting the item number even though we dont use it
Price = input('What is the unit price: '); % collecting price
Quantity = input('How many of the item are there?: '); % collecting the number of items
NumItems = NumItems + 1; % using a counter for the number of items
Cost = Price * Quantity; % Calculating the cost of the items bought
if NumItems <= 1 % if the number of items is less than or equal to one then the total cost is just the cost itself
TotalCost = Cost;
else % otherwise the totalCost is equal to the cost plus the previous cost
TotalCost = Cost + TotalCost;
end
end
fprintf('The total cost is: %d',TotalCost); % Print final statement
댓글 수: 0
채택된 답변
vidhathri bhat
2019년 6월 25일
Hi
Answer = input('Is there a new item? hit 1 for yes 0 for no: ','s'); % altering final condition
In this line you are reading input as character and in while condition you are comparing it with 1 as integer. That is why while condition is failing.
Answer = input('Is there a new item? hit 1 for yes 0 for no: ');
If you read the input as integer instead it should work.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Financial Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!