How to transform years into centuries

3 Ansichten (letzte 30 Tage)
Radoslav Gagov
Radoslav Gagov am 13 Apr. 2017
Beantwortet: RAMAKANT SHAKYA am 7 Feb. 2019
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 Kommentare
Guillaume
Guillaume am 13 Apr. 2017
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 am 7 Jun. 2017
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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

RAMAKANT SHAKYA
RAMAKANT SHAKYA am 7 Feb. 2019
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

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by