If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. Write a function called number2letters that returns the number of letters needed to write down the number n in

5 次查看(过去 30 天)
function t=number2letters(n)
number2letters(1)=3;
number2letters(2)=3;
number2letters(3)=5;
number2letters(4)=4;
number2letters(5)=4;
number2letters(6)=3;
number2letters(7)=5;
number2letters(8)=5;
number2letters(9)=4;
number2letters(13)=3;
number2letters(11)=6;
number2letters(12)=6;
number2letters(13)=8;
number2letters(14)=8;
number2letters(15)=7;
number2letters(16)=7;
number2letters(17)=9;
number2letters(18)=8;
number2letters(19)=8;
number2letters(20)=6;
number2letters(30)=6;
number2letters(40)=5;
number2letters(50)=5;
number2letters(60)=5;
number2letters(70)=7;
number2letters(80)=6;
number2letters(90)=6;
number2letters(100)=10;
number2letters(200)=10;
number2letters(300)=12;
number2letters(400)=11;
number2letters(500)=11;
number2letters(600)=10;
number2letters(700)=12;
number2letters(800)=12;
number2letters(900)=11;
for n=(1:999)
if (2<= log10(n))&& (log10(n)<3)
b=floor(x/100);
c=fix(mod(x,100)/10);
d=mod(mod(x,100),10);
t=number2letters(b)+10+number2letters(c)+number2letters(d);
elseif (1<= log10(n))&& (log10(n)<2)
c=fix(mod(x,100)/10);
d=mod(mod(x,100),10);
t=number2letters(c)+number2letters(d);
else
t= number2letters(n);
end
end
end
  6 个评论
Stephen23
Stephen23 2018-8-27
编辑:Stephen23 2018-8-27
@Lisa SU: do NOT name any variable inside the function with the same name as the function itself. This is a guaranteed path to confusing code and strange bugs.
@madhan ravi: perhaps n=5 for the example given in the question, but I agree that this is not really very clear: is the function supposed to calculate the sum from 1:n, as the example shows, or just for n?
madhan ravi
madhan ravi 2018-8-27
编辑:madhan ravi 2018-8-27
@Stephen cobeldick thank you neither do I understand the question.According to what I understand is for example n = 5 when this function is called the output should be 4 because it consists of four letters. I have a clue that it has something to do with strings or cells because inputs are characters such as five.

请先登录,再进行评论。

回答(1 个)

Pierre845
Pierre845 2018-8-27
Do a Switch .. Case it will be much cleaner.
Also, your function cannot work as you need conditional statements (if .. elseif ..)
function result = number2letters(n) switch n case 1 result = 3; case 2 result = 3; case 3 result = 5; % etc .. end

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by