Can you find the error in this code that aims to sum the digits of a string?
조회 수: 1 (최근 30일)
이전 댓글 표시
I wrote this code in order to sum the digits of any string, and to also create a loop that stops the summing process when the length of the sum is equal to a single digit.
What's wrong?
n = '12361927'
function d = sumdigits(n)
s=0
for i=1:length(n)
s=s+str2double(n(i))
end
end
s=sumdigits(n)
if length(str2num(s))==1
s=s
else
while length(str2num(s))~=1
if length(str2num(s))==1
break
else
s=sumdigits(s)
end
end
end
댓글 수: 0
채택된 답변
Stephen23
2019년 1월 6일
Simpler:
str = '12361927'
while numel(str)>1
num = sum(str-'0')
str = num2str(num)
end
Prints this in the command window:
str = 12361927
num = 31
str = 31
num = 4
str = 4
댓글 수: 3
Stephen23
2019년 1월 6일
편집: Stephen23
2019년 1월 6일
str-'0'
subtracts the character code for '0' (which is 48) from the character codes of the character array str. If all of the characters in str are digits then it converts the chracter representation of those digits into their numeric values, e.g.:
>> '1234'-'0'
ans =
1 2 3 4
추가 답변 (1개)
Stephan
2019년 1월 6일
Hi,
try :
n = '12361927'
s=num2str(sumdigits(n))
if strlength(s)==1
s=s;
disp('here')
else
while strlength(s)~=1
if strlength(s)==1
break
else
s=num2str(sumdigits(s))
end
end
end
function d = sumdigits(n)
s=0;
for i=1:length(n)
s=s+str2double(n(i));
end
d=s;
end
댓글 수: 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!