필터 지우기
필터 지우기

How to transform years into centuries

조회 수: 1 (최근 30일)
Radoslav Gagov
Radoslav Gagov 2017년 4월 13일
답변: RAMAKANT SHAKYA 2019년 2월 7일
Hey guys. I need to creat a function that transforms years in to centuries. I suppose i can do it with 30 if statements, but was wandering how we can do it in a smarter way.
Write a function called centuries that takes a positive integer smaller than or equal to 3000 representing a year as its input and returns a char vector with the century the given year falls into. If the input is invalid, the function returns the empty char vector '' (there is no space between the apostrophes). Centuries are specified using roman numerals. Note that we require the shortest legal roman number. For a complete list, refer to: http://www.romannumerals.co/roman-numerals-1-to-30. Note that a century goes from year 1 to 100, so for example, the XXth century ended on December 31st, 2000. As an example, the call
>> cent = centuries(1864);
will make cent equal to ‘XIX’.
  댓글 수: 3
Guillaume
Guillaume 2017년 4월 13일
If it works then you should submit it. It may be possible to make the conversion to roman numeral more generic but for the purpose of the assignment it's certainly good enough.
The only thing I'd change is to give meaningful names to all the variable.
Guillermo Varela Carbajal
Guillermo Varela Carbajal 2017년 6월 7일
Better to use ceil instead of floor
function cent = centuries (year)
if ~isscalar(year) || year<1 || year>3000 || year~=fix(year)
cent = '';
else
roman = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII','XVIII','XIX','XX','XXI','XXII','XXIII','XXIV','XXV','XXVI','XXVII','XXVIII','XXIX','XXX'};
cent = roman{ceil(year/100)};
end

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

답변 (1개)

RAMAKANT SHAKYA
RAMAKANT SHAKYA 2019년 2월 7일
function s= centuries(n)
p={'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII',' XVIII','XIX','XX','XXI','XXII','XXIII','XXIV','XXV','XXVI','XXVII','XXVIII','XXIX','XXX'};
d=length(n);
if d>1
n=-1;
end
if n>0&&n<=100&&n==fix(n)
s='I'; %for less than 100
elseif n>100&&n<=3000 && n==fix(n)
m=n/100;
r=ceil(m);
s=p{r};
else
s='';
end
end

카테고리

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