How to Repeat the script and determine if user input is Binary.

4 ビュー (過去 30 日間)
Faris Haroon
Faris Haroon 2020 年 4 月 18 日
コメント済み: Walter Roberson 2020 年 4 月 18 日
Hey guys, new to matlab and im having an issue trying to loop the script.
dec = 0;
base = 1;
bin = input('Enter a binary number:');
while bin >= 1
rem = mod(bin,10);
dec = dec + (rem * base);
bin = round(bin / 10);
base = base * 2;
end
disp(dec)
Thats my script. Its function is to convert binary numbers into decimal numbers which it does successful. But i need it to keep repeating (asking for user input) until an illegal number is inputted (anything other than 0 or 1). However when run this script just ends.
Also need help on displaying "not a binary number" if non binary number are inputted thanks

回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 4 月 18 日
編集済み: Walter Roberson 2020 年 4 月 18 日
If you need to keep repeating asking for input, then you need another while loop around what you have. The while loop can be
while true
since you want it to repeat forever.
Also need help on displaying "not a binary number" if non binary number are inputted thanks
In such a case, rem would not be either 0 or 1.
ps: watch out for negative numbers.
  2 件のコメント
Faris Haroon
Faris Haroon 2020 年 4 月 18 日
Thank you very much, putting a while loop around the whole script fixed my issue. However im still unable to filter out non-binary numbers as it still generates an output for non binary numbers. Thanks
Walter Roberson
Walter Roberson 2020 年 4 月 18 日
When you find a non-binary number, you should probably tell MATLAB to stop the loop.
Hint: if you stop the loop early, then bin>=1 will still be true after the loop, and if you detect that case then you would refrain from doing the disp()... and you would also want to exit the while true

サインインしてコメントする。


Mehmed Saad
Mehmed Saad 2020 年 4 月 18 日
  • regexp to find if number is between 2-9, if there exist any number, break the while loop
while(1)
bin = input('Enter a binary number:');
dec = 0;base = 1;
if(isempty(regexp(num2str(bin),'[2-9]', 'once')))
while bin >= 1
rem = mod(bin,10);
dec = dec + (rem * base);
bin = round(bin / 10);
base = base * 2;
end
disp(dec);
else
break;
end
end
disp('Not a valid input');

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by