C#
private static readonly int[] valori =
{1000, 900,
500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static readonly string[] simboli =
{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
C#
public static string ConvertiInNumeriRomano(int numero)
{
if (numero < 1 || numero > 2100)
throw new ArgumentOutOfRangeException(nameof(numero),
"Il numero deve essere compreso tra 1 e
2100.");
var risultato =
string.Empty;
for (int i = 0; i < valori.Length; i++)
{
while (numero >= valori[i])
{
numero -= valori[i];
risultato
+= simboli[i];
}
}
return risultato;
}
private void BtnConvertiNumeriRomani_Click(object sender, EventArgs e)
{
try
{
if (!int.TryParse(TxtNumeri.Text,
out int anno))
{
MessageBox.Show("Errore: inserire un numero intero valido.");
return;
}
string numeroRomano =
ConvertiInNumeriRomano(anno);
MessageBox.Show($"Numero romano: {numeroRomano}");
}
catch (ArgumentOutOfRangeException ex)
{
MessageBox.Show("Errore:" +
ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Errore:" + ex.Message);
}
}
Le opere pubblicate in questo blog sono sotto la licenza Creative Commons. Attribuzione- No commerciale e no derivate.
Nessun commento:
Posta un commento