How can I write a program to make someone input a 6 digit number and show a result of the summation of the 6 digits?

2 ビュー (過去 30 日間)
Anybody know the functions I need?

採用された回答

Stephen23
Stephen23 2014 年 12 月 17 日
Try this:
sum(input('Enter a six digit number:','s')-'0')

その他の回答 (2 件)

Sudharsana Iyengar
Sudharsana Iyengar 2014 年 12 月 17 日
you can try this simple program by using fix. This writes a six digit number as sum of ones hundreds thousands etc.
This code can be made better by using recursion.
Here is the Program
n = input('Enter a six digit number:');
z=fix(n/100000);
y=fix(n-z*100000);
w=fix(y/10000);
y2=fix(y-w*10000);
w2=fix(y2/1000);
y3=fix(y2-w2*1000);
w3=fix(y3/100);
y4=fix(y3-w3*100);
w4=fix(y4/10);
y5=fix(y4-w4*10);
w5=fix(y5);
z*100000
w*10000
w2*1000
w3*100
w4*10
w5*1
z,w,w2,w3,w4,and w5 store the values you can save them in an array or use it for any other manipulation.

Thorsten
Thorsten 2014 年 12 月 17 日
編集済み: Thorsten 2014 年 12 月 17 日
Convert the number to a string, and then convert each character of the string to the corresponding value (using arrayfun to work on each element of the string), and sum the resulting values:
num = 123456; % sample number
sumofdigits = sum(arrayfun(@(x) double(x)- double('0'), int2str(num)));
  3 件のコメント
Andrei Bobrov
Andrei Bobrov 2014 年 12 月 18 日
just
num = 123456;
sumofdigits = sum(int2str(num) - '0');
Thorsten
Thorsten 2014 年 12 月 19 日
編集済み: Thorsten 2014 年 12 月 19 日
Dear Sudharsana,
The idea to convert the number to a string. In a string, each digit has a numerical value depending on the encoding, usually ASCII. For example, the string '123456' is represented as [49 50 51 52 53 54]. The nice thing in Matlab is that you can treat this string just as an array of numbers. If you now subtract the value of the character '0', namely 48, from your array, you get an array of numbers [ 1 2 3 4 5 6]. Use sum to sum all values, et Voilá! Please note that Steven and Andrei proposed shorter and more elegant ways to do this.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by