a013.
羅馬數字
--
NPSC 模擬試題
| From: [114.26.202.123] |
發表日期
:
2022-05-08 21:17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int rome(char); /* 羅馬變數字 */
char* become_rome(int,char *); /* 數字變羅馬 */
struct data
{
char str1[20];
char str2[20];
struct data *next;
} ;
typedef struct data NODE;
int main(void)
{
int flag=0;
char str[20];
NODE *first,*current,*previous;
while(1)
{
current=(NODE *)malloc(sizeof(NODE));
scanf("%s",¤t->str1);
if(current->str1[0]==35)
break;
scanf(" %s",¤t->str2);
if(flag==0)
{
first=current;
flag=1;
}
else
previous->next=current;
current->next=NULL;
previous=current;
}
current=first;
while(current!=NULL)
{
int i=0,total1=0,total2=0;
while(current->str1[i]!='\0')
{
if(rome(current->str1[i]) < rome(current->str1[i+1]) && current->str1[i+1]!='\0')
{
total1+=(rome(current->str1[i+1])-rome(current->str1[i]));
i++;
}
else
total1+=rome(current->str1[i]);
i++;
}
i=0;
while(current->str2[i]!='\0')
{
if(rome(current->str2[i]) < rome(current->str2[i+1]) && current->str2[i+1]!='\0')
{
total2+=(rome(current->str2[i+1])-rome(current->str2[i]));
i++;
}
else
total2+=rome(current->str2[i]);
i++;
}
if((total1-total2)==0)
printf("ZERO");
else
{
memset(str,0,20);
printf("%s",become_rome(total1-total2,str));
}
printf("\n");
current=current->next;
}
return 0;
}
int rome(char ch)
{
int n;
switch(ch)
{
case'I':
n=1;
break;
case'V':
n=5;
break;
case'X':
n=10;
break;
case'L':
n=50;
break;
case'C':
n=100;
break;
case'D':
n=500;
break;
case'M':
n=1000;
break;
}
return n;
}
char* become_rome(int num,char *str)
{
int i=0;
while(num>=1000)
{
num-=1000;
str[i]='M';
i++;
}
if(num>=900)
{
num-=900;
str[i]='C';
str[i+1]='M';
i+=2;
}
while(num>=500)
{
num-=500;
str[i]='D';
i++;
}
if(num>=400)
{
num-=400;
str[i]='C';
str[i+1]='D';
i+=2;
}
while(num>=100)
{
num-=100;
str[i]='C';
i++;
}
if(num>=90)
{
num-=90;
str[i]='X';
str[i+1]='C';
i+=2;
}
while(num>=50)
{
num-=50;
str[i]='L';
i++;
}
if(num>=40)
{
num-=40;
str[i]='X';
str[i+1]='L';
i+=2;
}
while(num>=10)
{
num-=10;
str[i]='X';
i++;
}
if(num>=9)
{
num-=9;
str[i]='I';
str[i+1]='X';
i+=2;
}
while(num>=5)
{
num-=5;
str[i]='V';
i++;
}
if(num>=4)
{
num-=4;
str[i]='I';
str[i+1]='V';
i+=2;
}
while(num>0)
{
num-=1;
str[i]='I';
i++;
}
return str;
}