Algorithm in C to convert arabic number to roman number

8

How to do this conversion?

It does not have to be the algorithm ready, I wanted a help at least in logic.

    
asked by anonymous 26.05.2014 / 00:41

2 answers

9
#include <stdio.h>

int main () {
    for (int i = 1; i < 3000; i++) {
        int numero = i;
        char *romanos[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
        int arabicos[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
        // acha a quantidade de elementos no array
        int indice = (sizeof(arabicos) / sizeof(arabicos[0])) - 1;
        while (numero > 0) {
            if (numero >= arabicos[indice]) {
                printf("%s", romanos[indice]);
                numero -= arabicos[indice];
            } else {
                indice--;
            }
        }
        printf("\n");
    }
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

To do the conversion of 5000 numbers (there are controversies about the 4000 already requiring the "upper dash") upwards complicates because you need to use 2 lines or Unicode characters. Adapt to the way you feel best and fulfill your need.

    
26.05.2014 / 02:34
5
#include <stdio.h>

void ArabicToRoman (unsigned int numero, char *resultado) 
{
    char *centenas[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    char *dezenas[]  = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    char *unidades[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    int   size[] = { 0, 1, 2, 3, 2, 1, 2, 3, 4, 2,};

    while (numero >= 1000)
    {
        *resultado++ = 'M';
         numero -= 1000;
    }

    strcpy (resultado, centenas[numero / 100]); resultado += size[numero / 100]; numero = numero % 100;
    strcpy (resultado, dezenas[numero / 10]);   resultado += size[numero / 10];  numero = numero % 10;
    strcpy (resultado, unidades[numero]);       resultado += size[numero];
}

int main()
{
    char *romanNumber = malloc(sizeof(char) * 1024);
    int numero;

    puts("Digite um valor a ser convertido: ");
    scanf("%d", &numero);

    ArabicToRoman(numero, romanNumber);
    printf("O valor %d equivale %s em romano\n", numero, romanNumber);

    return 0;
}

For example, take a case where the number to be converted to Roman numeration is 635 . numero / 100 will result in 6 , in this case, the search set is centenas , 6 equals DC .

Then numero = numero % 100 will result in 35 , then the search set will be dezenas . numero / 10 will result in 3 which will result XXX , then in numero = numero % 10 will result in 5 , where the search set is unidades which will give% .

So the end result is V .

Sample removed DCXXXV .

    
26.05.2014 / 01:28