#13391: C 解答


chang0719 (y仔)

學校 : 臺北市立大直高級中學
編號 : 50462
來源 : [150.117.232.160]
最後登入時間 :
2018-02-26 22:45:32
a013. 羅馬數字 -- NPSC 模擬試題 | From: [150.117.232.160] | 發表日期 : 2018-02-11 16:33

#include <stdio.h>
#include <string.h>

int convert_roman_to_int(char *);
void convert_int_to_roman(int);

int main() {
char number1[15],number2[15],answer[15];
int r1=0,r2=0,result;


while (scanf("%s", number1) && number1[0] != '#') {
scanf("%s", number2);

r1 = convert_roman_to_int(number1);
r2 = convert_roman_to_int(number2);
result = (r1>r2?r1-r2:r2-r1);
convert_int_to_roman(result);
}
return 0;
}

int convert_roman_to_int(char *number) {
int sum=0;
int i;

for (i=0;i<strlen(number);i++){
switch (number[i]) {
case 'I':
if (number[i+1] == 'V')
sum += 4,i++;
else if (number[i+1] == 'X')
sum += 9,i++;
else
sum += 1;
break;
case 'V':
sum += 5;
break;
case 'X':
if (number[i+1] == 'L')
sum += 40,i++;
else if (number[i+1] == 'C')
sum += 90,i++;
else
sum += 10;
break;
case 'L':
sum += 50;
break;
case 'C':
if (number[i+1] == 'D')
sum += 400,i++;
else if (number[i+1] == 'M')
sum += 900,i++;
else
sum += 100;
break;
case 'D':
sum += 500;
break;
case 'M':
sum += 1000;
}
}
return sum;
}

void convert_int_to_roman(int result) {
const char *table1[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
const char *table2[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
*table3[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
*table4[] = {"","M","MM","MMM"};

if(result == 0)
printf("ZERO\n");
else
printf("%s%s%s%s\n",table4[(int)(result/1000)],table3[(int)(result/100-10*(result/1000))],table2[(int)(result/10-10*(result/100))],table1[(int)(result-10*(result/10))]);
}

 
ZeroJudge Forum