002
30.05.2005, 21:55 Uhr
0xdeadbeef
Gott (Operator)
|
C++: |
#include <ctype.h> #include <stdio.h> #include <string.h>
#define BUFLEN 100
char *arabic2roman(char *buf, int x) { static char const *const rom_str_array[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; static int const rom_num_array[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, 0 };
int ix; char *p = buf;
for(ix = 0; rom_num_array[ix]; ++ix) { while(x >= rom_num_array[ix]) { x -= rom_num_array[ix]; p += strlen(strcpy(p, rom_str_array[ix])); } }
return buf; }
int rom_char_val(char c) { switch(tolower(c)) { case 'm': return 1000; case 'd': return 500; case 'c': return 100; case 'l': return 50; case 'x': return 10; case 'v': return 5; case 'i': return 1; } return 0; }
int roman2arabic(char const *buf) { int ix, ret = 0, cur_val, next_val;
for(ix = 0; isalpha(buf[ix]); ++ix) { if(cur_val = rom_char_val(buf[ix])) { next_val = rom_char_val(buf[ix + 1]); if(cur_val < next_val) { ret -= cur_val; } else { ret += cur_val; } } else { printf("%c %d %d\n", buf[ix], cur_val, ix); return 0; } }
return ret; }
int main(void) { char buf[BUFLEN]; int x, check;
fgets(buf, BUFLEN, stdin);
check = sscanf(buf, "%d", &x);
if(check == 1 && x < 4000 && x > 0) { puts(arabic2roman(buf, x)); } else if(x = roman2arabic(buf)) { printf("%d\n", x); } else { puts("Fehlerhafte Eingabe."); }
return 0; }
|
-- Einfachheit ist Voraussetzung für Zuverlässigkeit. -- Edsger Wybe Dijkstra Dieser Post wurde am 30.05.2005 um 21:58 Uhr von 0xdeadbeef editiert. |