While loop with if function

11 views (last 30 days)
Ken L
Ken L on 30 Jan 2021
Commented: Ken L on 2 Feb 2021
Hi, need some help on whie loop and if function.
E.g,
Amount =$1-500
type = a or b
How should I write in mathlab, if I wan if the amount between 1-500 and if the type is "a" then show the 'a" result else showing "b" result. And after that will ask whether user want to continue the process or not.

Accepted Answer

Walter Roberson
Walter Roberson on 30 Jan 2021
if 1 <= amount & amount <= 500 & strcmp(type, 'a')
  9 Comments
Walter Roberson
Walter Roberson on 1 Feb 2021
while true
name = input("Enter name:","s");
address = input("Enter address:","s");
purchase_amount = input("Enter amount of purchase:");
purchase_type = input("Enter type of purchase (L for type L/ D for type D):","s");
fail = false;
if strcmpi(purchase_type, "D") && purchase_amount >= 0 && purchase_amount <= 250
discount = 0.95;
net_amount = purchase_amount*discount;
elseif strcmpi(purchase_type, "D") && purchase_amount >= 251 && purchase_amount <= 570
discount = 0.924;
net_amount = purchase_amount*discount;
elseif strcmpi(purchase_type, "D") || strcmpi(purchase_type, "L")&& purchase_amount >= 0 && purchase_amount <= 250
discount = 1;
net_amount = purchase_amount*discount;
elseif strcmpi(purchase_type, "D") || strcmpi(purchase_type, "L")&& purchase_amount >= 251 && purchase_amount <= 570
discount = 0.95;
net_amount = purchase_amount*discount;
else
fprintf ("Invalid type.\n")
fail = true;
end
if ~fail
fprintf("Name: %s\n",name);
fprintf("Address: %s\n",address);
fprintf("Net Amount: $%d\n",net_amount);
end
prompt = input("Do you wish to continue to purchase (Y for Yes/ N for No):","s");
if ~strcmpi(prompt, 'Y')
break;
end
end
fprintf("Goodbye.\n");
Ken L
Ken L on 2 Feb 2021
Hi Walter, thank you very much, the code worked perfectly, really appreciate your help.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!