rtoi---``roman to integer''
Peter Monta
monta at cmu-cs-g.ARPA
Mon Apr 29 01:45:11 AEST 1985
Here is a C function that converts roman numeral strings to integers. It
doesn't complain about syntax errors (I seem to remember my junior-high-school
teacher insisting that ``IC'' is wrong, should be ``XCIX''; something like
only one ``level'' of subtractive notation permitted). Anyway, if these
semantics are wrong, tell me about it. (Thank goodness for positional
notation.)
Peter Monta
monta at cmu-cs-g
..!rocherster!cmu-cs-pt!cmu-cs-g!monta
-----------------------------------Cut Here-----------------------------------
#include <stdio.h>
#define max_table 7
static struct { char name; int value } table[max_table] =
{ {'i',1}, {'v',5}, {'x',10}, {'l',50}, {'c',100}, {'d',500}, {'m',1000} };
int rtoi(s)
char s[];
{ int i,j,old,new,sum;
sum = 0; old = 0;
for (i=strlen(s)-1; i>=0; i--)
for (j=0; j<max_table; j++)
if (table[j].name==s[i]) {
new = table[j].value;
if (new < old) sum -= new; else sum += new;
old = new;
break; }
return sum; }
main()
{ char s[50];
for (;;) {
printf("roman numeral: ");
scanf("%s",s);
printf("value is %d\n",rtoi(s)); } }
More information about the Comp.sources.unix
mailing list