How can I display the sum of the digits of a number entered by a user?

조회 수: 37 (최근 30일)
Rodha M
Rodha M 2020년 9월 23일
댓글: Rodha M 2020년 9월 23일
I am new to MATLAB, and I want to know how can I display the sum of the digits of a number entered by a user, I started the program but I got stuck.
x=input('Please enter a number: '); %asks the user to enter a number
n= strlength(abs(x) + "") %count the number of digits in that number
y=fprintf('The number of digits of %d is %d \n',x,n);
I would appreciate it if anyone could help. Thank you in advance.

채택된 답변

David Hill
David Hill 2020년 9월 23일
편집: David Hill 2020년 9월 23일
n=length(num2str(x));%number of digits
s=sum(num2str(x)-'0');%sum of digits

추가 답변 (2개)

Cris LaPierre
Cris LaPierre 2020년 9월 23일

KSSV
KSSV 2020년 9월 23일
n = 3434;
digits = dec2base(N,10) - '0' ;
iwant = sum(digits)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by