How to output individual digits from a user input of 2 digit numbers?
조회 수: 2 (최근 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
댓글 수: 0
채택된 답변
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
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
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))
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!