/* Program: ROMAN.CPP Author : Kim Moser Date : 13 May, 1992 System : IBM PC / Borland C++ 3.0 Descrip: Convert Roman numerals to Arabic and vice versa Usage : */ #include #include #include static int roman_digit_value(int ch); static int roman_digit_value(int ch) { switch (ch) { case 'M': return (1000); case 'C': return (100); case 'L': return (50); case 'X': return (10); case 'V': return (5); case 'I': return (1); default: return (0); } } static int is_roman_digit(int ch); static int is_roman_digit(int ch) { return (roman_digit_value(ch)); } /* I 1 II 2 III 3 IV 4 V 5 VI 6 VII 7 VIII 8 IX 9 X 10 XI 11 XII 12 XIII 13 XIV 14 XV 15 XVI 16 */ static int roman2arabic(char* s); static int roman2arabic(char* s) { int arabic=0; int ch; int ch_val, prev_val=0; for (int i=0; (ch = toupper(s[i])) != '\0'; i++) { if (is_roman_digit(ch)) { ch_val = roman_digit_value(ch); if (prev_val && (ch_val > prev_val)) { // XIV // ^ // Subtract 'I', add 'V': arabic -= 2*prev_val; } // XIV // ^ // Add 'V': arabic += ch_val; } else { arabic = 0; break; } prev_val = roman_digit_value(ch); } return (arabic); } static char* chrcat(char* s, int ch); static char* chrcat(char* s, int ch) { int len = strlen(s); s[len] = ch; s[len+1] = '\0'; return (s); } static char* arabic2roman(int n); static char* arabic2roman(int n) { static char roman[20]; int digit, prev_digit='\0'; int value, prev_value=0; roman[0] = '\0'; while (n) { for (int i=0; i < 6; i++) { switch (i) { case 0: digit = 'M'; break; case 1: digit = 'C'; break; case 2: digit = 'L'; break; case 3: digit = 'X'; break; case 4: digit = 'V'; break; case 5: digit = 'I'; break; default: // Should never happen roman[0] = '\0'; return (roman); } // 1992 == MCMLXLII // 992 M value = roman_digit_value(digit); if ((digit != 'M') && (n / value > 3)) { while (n / value) { chrcat(roman, digit); n -= value; } } else { while (n && (n >= value)) { chrcat(roman, digit); n -= value; } } prev_digit = digit; prev_value = value; } } return (roman); } main() { char roman[20]; cout << "\n\nGive me a Roman number: "; cin.width(sizeof(roman)-1); cin >> roman; cout << roman << " = " << roman2arabic(roman) << '\n'; return (0); }