How to transform years into centuries

2 次查看(过去 30 天)
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
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 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by