need solution asap for my hw about summing each character in student number that we input the data
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Ezgi kaya
il 22 Mag 2020
Commentato: Abdolkarim Mohammadi
il 22 Mag 2020
num=input('enter your student number here : ');
number is 20758562
how can i sum each number ?
0 Commenti
Risposta accettata
Abdolkarim Mohammadi
il 22 Mag 2020
Modificato: Abdolkarim Mohammadi
il 22 Mag 2020
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 Commenti
Steven Lord
il 22 Mag 2020
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
il 22 Mag 2020
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.
Più risposte (1)
Stephen23
il 22 Mag 2020
The MATLAB way:
>> str = input('enter your student number here: ','s');
enter your student number here: 20758562
>> num = sum(str-'0')
num = 35
0 Commenti
Vedere anche
Categorie
Scopri di più su Data Type Identification in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!