How to output individual digits from a user input of 2 digit numbers?
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
% 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
0 commentaires
Réponse acceptée
Voss
le 17 Fév 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 commentaires
Voss
le 18 Fév 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
Plus de réponses (1)
Geoff Hayes
le 17 Fév 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))
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!