switch case and menu command
16 ビュー (過去 30 日間)
古いコメントを表示
I'm trying to create a code that convert in,ft,cm,mm to m(meters). but as i run the code, it give me a list at the left side. what im trying to do is first i will chose what i want to be converted i'ts either in,ft,cm, and mm, then i will enter a number to be converted then the result will show or pop up.
choice = menu('Choose a unit','in','ft','cm','mm');
m = input('Input a value to be converted:');
result = (m);
switch choice
case 'in'
result = result*0.0254;
case 'cm'
result = result/100;
case 'mm'
result = result/1000;
case 'ft'
result = result/0.3048;
end
0 件のコメント
回答 (2 件)
Walter Roberson
2017 年 8 月 20 日
menu() does not return the string that was chosen: it returns the index of the string. So for example if 'ft' were chosen, that is the second possibility, so menu() would return 2.
0 件のコメント
Stephen23
2017 年 8 月 20 日
編集済み: Stephen23
2017 年 8 月 20 日
The menu documentation tell us that menu returns the index of the selected button, not the string of the button. Try this:
U = {'in','ft','cm','mm'};
C = menu('Choose a unit',U{:});
V = str2double(input('Input a value to be converted: ','s'));
switch U{C}
case 'in'
... your code
end
Note that I also replaced the insecure input(...) call with str2double(input(...,'s')), which prevents any arbitrary code being executed.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!