How to transform years into centuries

3 vues (au cours des 30 derniers jours)
Radoslav Gagov
Radoslav Gagov le 13 Avr 2017
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 commentaires
Guillaume
Guillaume le 13 Avr 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 le 7 Juin 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

Connectez-vous pour commenter.

Réponses (1)

RAMAKANT SHAKYA
RAMAKANT SHAKYA le 7 Fév 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

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by