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

조회 수: 1 (최근 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
  댓글 수: 1
Lisa SU
Lisa SU 2018년 8월 27일
Excuse me,I can't understand '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