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

9 Ansichten (letzte 30 Tage)
% 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

Akzeptierte Antwort

Voss
Voss am 17 Feb. 2022
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 Kommentare
Jacob Boulrice
Jacob Boulrice am 17 Feb. 2022
Bearbeitet: Jacob Boulrice am 17 Feb. 2022
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 am 18 Feb. 2022
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Geoff Hayes
Geoff Hayes am 17 Feb. 2022
@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))

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by