想法是用getchar取字母
因為兩組字母間有空白
可以把它們拆成x和y
再把x和y差的絕對值丟進陣列
讀到#時跳出while
然後用除法印字母
在我的 vsc++答案會對
但是網站編譯答案都會差1
I I ------------- I
MM II ----------- MCMXCII
#include <stdio.h>
#include <stdlib.h>
int tonum( char );
int main()
{
int i, d = 0, x, y, z[10] = {0};
char *t = NULL, a[10] = { 0 };
while (1)
{
for (i = 0; (a[i] = getchar()) != '\n'; i++)
continue;
if (a[0] == '#')
break;
for (t = a, i = 0, x = 0, y = 0; *t != '\n'; t++)
{
if (*t == ' ')
i++;
else if(*t != ' ')
{
if (i == 0)
x = x + tonum(*t);
if (i == 1)
y = y + tonum(*t);
}
}
z[d] = ((x - y) >= 0) ? (x-y): -(x-y);
d++;
printf("%d %d", x, y);
}
for (i = 0; i < d; i++)
{
if (z[i] == 0)
printf("ZERO");
while (z[i] / 1000 > 0)
{
printf("M");
z[i] -= 1000;
}
while (z[i] / 900 > 0)
{
printf("CM");
z[i] -= 900;
}
while (z[i] / 500 > 0)
{
printf("D");
z[i] -= 500;
}
while (z[i] / 100 > 0)
{
printf("C");
z[i] -= 100;
}
while (z[i] / 90 > 0)
{
printf("XC");
z[i] -= 90;
}
while (z[i] / 50 > 0)
{
printf("L");
z[i] -= 50;
}
while (z[i] / 10 > 0)
{
printf("X");
z[i] -= 10;
}
while (z[i] / 9 > 0)
{
printf("IX");
z[i] -= 9;
}
while (z[i] / 5 > 0)
{
printf("V");
z[i] -= 5;
}
while (z[i] / 1 > 0)
{
printf("I");
z[i] -= 1;
}
printf("\n");
}
system("PAUSE");
return 0;
}
int tonum(char x)
{
switch (x)
{
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
break;
}
}