Keep prompting user instead of hitting run each time.
1 回表示 (過去 30 日間)
古いコメントを表示
I would like this code to run in a loop that displays the cost of the package, then loops back to the beginning to prompt the user again to enter a weight (as opposed to me having to run the code each time I want the prompt). I'm sure it's really simple, I've tried putting in a return statement in the code and tried a while loop but I don't know.
weight=0;
weight=input('Input a weight');
if weight<=2
cost=15;
disp(cost);
elseif weight<= 70
cost=(15+((weight-2)*5));
disp(cost);
elseif weight <= 100
cost= (30+((weight-2)*5));
disp(cost);
else
disp('No Weight over 100');
end
0 件のコメント
回答 (2 件)
Rik
2018 年 10 月 30 日
You can wrap your code in a while loop, but that will force the user to hard-break out of your code (ctrl-C on Windows). A nicer solution is to provide the user with the option of exiting.
while true
weight=input('Input a weight (enter negative to exit)');
if weight<0
break
end
if weight<=2
cost=15;
disp(cost);
elseif weight<= 70
cost=(15+((weight-2)*5));
disp(cost);
elseif weight <= 100
cost= (30+((weight-2)*5));
disp(cost);
else
disp('No Weight over 100');
end
end
0 件のコメント
Walter Roberson
2018 年 10 月 30 日
Put
while true
At the top, and put
end
At the bottom.
Next question is how you are going to get out of the loop instead of having to enter values for the rest of the life of the computer.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!