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.

 채택된 답변

zhenhan weng
zhenhan weng 2015년 9월 18일

0 개 추천

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

질문:

2015년 9월 18일

댓글:

2015년 9월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by