How to output individual digits from a user input of 2 digit numbers?

8 次查看(过去 30 天)
% This is my code so far. Say n=10, output would be: "thanks, the digits are 10 and 10"
% In this case, I want the output to be: "thanks, the digits are 1 and 0"
% I understand the n's in my first fprintf are going to display n.
% But I *think* it may have to do with this line, or maybe redefining n after the input.
% if anyone can lead me in the right direction I would appreciate it!
% Also, people have suggested while loops and some other functions like str2double, but my class hasn't covered this yet.
%--------------------------------------------------CODE BELOW-------------------------------------------------------------------
clc, clear;
n = input('Enter a two-digit number: ');
proper_input = (n == floor(n) && n >= -99 && n <= -10 || n <= 99 && n >= 10);
if proper_input == 1
fprintf("\nthanks, the digits are %d and %d",n,n)
else
fprintf('Bad')
end

采纳的回答

Voss
Voss 2022-2-17
A while loop would be useful if you need to handle numbers with any number of digits, but since you're only doing 2-digit numbers here, you can do it like this:
clc, clear;
n = input('Enter a two-digit number: ');
proper_input = (n == floor(n) && (n >= -99 && n <= -10) || (n <= 99 && n >= 10));
if proper_input == 1
n = abs(n);
m = floor(n/10);
n = n-m*10;
fprintf("\nthanks, the digits are %d and %d",m,n)
else
fprintf('Bad')
end
  2 个评论
Jacob Boulrice
Jacob Boulrice 2022-2-17
编辑:Jacob Boulrice 2022-2-17
I did try this. And it seemed like the digits were seperated, however, in the command window two boxes like [] were outputted.. weird.
"Thanks, the digits are [] and []"
edit... Nevermind. I forgot to change the %s to %d!
It works now, thank you. I'll have to disect what you did!
Voss
Voss 2022-2-18
Glad it's working!
The abs() is to be able to treat positive and negative inputs the same, i.e., what follows only has to work for positive numbers.
floor(n/10) gives you the ten's digit, e.g., 89/10 = 8.9 -> floor(8.9) = 8
Then subtracting 10 times the ten's digit from the original number gives you the one's digit, e.g., 89-8*10=9

请先登录,再进行评论。

更多回答(1 个)

Geoff Hayes
Geoff Hayes 2022-2-17
@Jacob Boulrice - rather than having n be an integer, perhaps it should be a string so that you can parse the first and second character. For example, if you update your call to input as shown at returns the entered text, then you can just pull the first and second digit from the string
fprintf("\nthanks, the digits are %s and %s",n(1),n(2))

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by