need solution asap for my hw about summing each character in student number that we input the data

조회 수: 1 (최근 30일)
num=input('enter your student number here : ');
number is 20758562
how can i sum each number ?

채택된 답변

Abdolkarim Mohammadi
Abdolkarim Mohammadi 2020년 5월 22일
편집: Abdolkarim Mohammadi 2020년 5월 22일
num = input('enter your student number here : ');
NumChar = num2str (num);
MySum = 0;
for i1 = 1:numel (NumChar)
MySum = MySum + str2double (NumChar(i1));
end
fprintf ('Sum of the numbers is %d', MySum);
  댓글 수: 3
Steven Lord
Steven Lord 2020년 5월 22일
Does your function work for student number 12345678901234567890? Since it consists of the digits 0 through 9 twice each, the sum should be 90.
Abdolkarim Mohammadi
Abdolkarim Mohammadi 2020년 5월 22일
You are right. This code does not work for that large numbers that do not fit into double. Stephen's answer is the correct one.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2020년 5월 22일
The MATLAB way:
>> str = input('enter your student number here: ','s');
enter your student number here: 20758562
>> num = sum(str-'0')
num = 35

카테고리

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