Roman Numeral Program
faustus at ucbcad.UUCP
faustus at ucbcad.UUCP
Fri Apr 26 17:04:53 AEST 1985
> Do you have a program that either converts numbers to roman numerals
> or (especially!) converts roman numerals to numbers.
Here is one: actually this prints the date in Roman numerals, but
the routine prom() does the real stuff...
Wayne
/* RCS Info: $Revision: 1.1 $ on $Date: 85/04/18 17:44:51 $
* $Source: /cad1/faustus/src/misc/RCS/rdate.c,v $
* Copyright (c) 1985 Wayne A. Christopher, U. C. Berkeley CAD Group
*
* Print the date in roman numerals.
*/
main()
{
char buf[64], s[3][16], nn[5][16], *prom();
int q, p[2], n[5];
pipe(p);
if(fork() == 0) {
dup2(p[1], 1);
execl("/bin/date", "date", 0);
}
q = read(p[0], buf, 64);
buf[q] = '\0';
sscanf(buf, " %s %s %d %d:%d:%d %s %d ", s[0], s[1], &n[0], &n[1],
&n[2], &n[3], s[2], &n[4]);
for(q = 0; q < 5; q++)
strcpy(nn[q], prom(n[q]));
printf("%s %s %s %s:%s:%s %s %s\n", s[0], s[1], nn[0], nn[1],
nn[2], nn[3], s[2], nn[4]);
exit(0);
}
/* Render number in Roman Numerals. Should be unsigned... Returns
* pointer to the rendering. Problems with static data, etc.
*/
char *
prom(num)
register unsigned int num;
{
register int pos = 0;
register int *i, k;
register char *j;
static char rbuf[64]; /* Bad assumption? */
static int ndigits[] = { 1000, 500, 100, 50, 10, 5, 1, 0 } ;
static char ddigits[] = { 'M', 'D', 'C', 'L', 'X', 'V', 'I', 'Z' } ;
if(num == 0)
return("Z"); /* Well, what do we do? */
while(num > 0) {
for((i = ndigits, j = ddigits); *i; (i++, j++)) {
if(num >= *i) {
rbuf[pos++] = *j;
num -= *i;
break;
}
/* If you are on an even index in the array, the
* digit to use for filling in (e.g. IX = 9) is
* *i / 10, otherwise use *i / 5 (to make sure
* that it is a power of 10).
*/
k = (!((ndigits - i) % 2) ? (*i / 10) : (*i / 5));
if(num >= (*i - k)) {
rbuf[pos++] = *(j +
(((ndigits - i) % 2) ? 1 : 2));
rbuf[pos++] = *j;
num -= (*i - k);
break;
}
}
}
rbuf[pos] = '\0';
return(rbuf);
}
More information about the Comp.sources.unix
mailing list