How do I loop a script?

1 view (last 30 days)
Bryan Wong
Bryan Wong on 18 Sep 2015
Commented: Bryan Wong on 18 Sep 2015
Write a script that will first prompt the user for a distance in kilometers (with error check that the input distance can’t be negative). Then, the script will print the cost of the travel by walking, by motorcycle, by car and by plane, knowing that: walking, motor-cycle, car and plane travel cost 0, 0.22, 0.26 and 0.78 SGD per kilometer respectively walking can’t be done for more than 20 kilometers, motor-cycle travel can’t be done for more than 200 kilometers, car travel can’t be done for more than 800 kilometers, plane travel can’t be done for less than 100 kilometers, For example, the output will look like this: Enter the distance in kilometer: 12 The cost by walking is free ! The cost by motorcycle is 2.6 SGD The cost by car is 3.1 SGD You travel is too short to be done by plane.
I have written the following:
%This script evaluates if it's feasible to travel by different means and
%its cost
%First it prompts users for a distance in km
Distance=input('Please input the distance you will travel in kilometres: ');
%Now we list the cases
%error check
if Distance < 0
disp('DISTANCE CANNOT BE NEGATIVE!!')
Distance=input('Please input the distance you will travel in kilometres: ');
end
%for walking
if Distance > 20
disp('Your travel is too long to be done by walking');
elseif Distance <= 20
disp('The cost by walking is free!');
end
%for biking
if Distance > 200
disp('Your travel is too long to be done by biking');
elseif Distance <= 200
fprintf('The cost by motorcycle is %.2f SGD\n',Distance*0.22);
end
%for driving
if Distance > 800
disp('Your travel is too long to be done by driving');
elseif Distance <= 800
fprintf('The cost by driving is %.2f SGD\n',Distance*0.26);
end
%for plane
if Distance <= 100
disp('Your travel is too short to be done by plane');
elseif Distance > 100
fprintf('The cost by flying is %.2f SGD\n',Distance*0.78);
end
The 1st error check is fine when I key a negative number for the 1st time. However, when I key a negative number again, it calculates the rest of the script ignoring the error check.

Accepted Answer

zhenhan weng
zhenhan weng on 18 Sep 2015
while Distance < 0
disp('DISTANCE CANNOT BE NEGATIVE!!')
Distance=input('Please input the distance you will travel in kilometres: ');
end
:)

More Answers (0)

Categories

Find more on Graph and Network Algorithms 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!