Borrar filtros
Borrar filtros

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

11 visualizaciones (últimos 30 días)
% 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

Respuesta aceptada

Voss
Voss el 17 de Feb. de 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 comentarios
Jacob Boulrice
Jacob Boulrice el 17 de Feb. de 2022
Editada: Jacob Boulrice el 17 de Feb. de 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 el 18 de Feb. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Geoff Hayes
Geoff Hayes el 17 de Feb. de 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))

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by