迴圈
輸入兩字串
依規則計算其值並相減取絕對值
再依其規則輸出
#include <cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int calc(string str);
void print(int value, char one, char five, char ten);
int main()
{
string A, B;
int result;
while(cin >> A >> B && A != "#")
{
result = abs(calc(A) - calc(B));
if(result == 0)
cout << "ZERO";
else
{
print( result/1000 , 'M', '?', '?');
print( (result/100)%10 , 'C', 'D', 'M');
print( (result/10)%10 , 'X', 'L', 'C');
print( result%10 , 'I', 'V', 'X');
}
cout << endl;
}
return 0;
}
int calc(string str)
{
int total = 0;
for(int i = 0; i < str.length(); i++)
{
if(str[i] == 'M')
total += 1000;
else if(str[i] == 'D')
total += 500;
else if(str[i] == 'C' && str[i+1] != 'M' && str[i+1] != 'D')
total += 100;
else if(str[i] == 'C' && str[i+1] == 'M'){
total += 900; i++;}
else if(str[i] == 'C' && str[i+1] == 'D'){
total += 400; i++;}
else if(str[i] == 'L')
total += 50;
else if(str[i] == 'X' && str[i+1] != 'L' && str[i+1] != 'C')
total += 10;
else if(str[i] == 'X' && str[i+1] == 'C'){
total += 90; i++;}
else if(str[i] == 'X' && str[i+1] == 'L'){
total += 40; i++;}
else if(str[i] == 'V')
total += 5;
else if(str[i] == 'I' && str[i+1] != 'V' && str[i+1] != 'X')
total += 1;
else if(str[i] == 'I' && str[i+1] == 'X'){
total += 9; i++;}
else if(str[i] == 'I' && str[i+1] == 'V'){
total += 4; i++;}
}
return total;
}
void print(int value, char one, char five, char ten)
{
switch(value)
{
case 9:
printf("%c%c", one, ten);
return;
case 8:
printf("%c%c%c%c", five, one, one, one);
return;
case 7:
printf("%c%c%c", five, one, one);
return;
case 6:
printf("%c%c", five, one);
return;
case 5:
printf("%c", five);
return;
case 4:
printf("%c%c", one, five);
return;
case 3:
printf("%c%c%c", one, one, one);
return;
case 2:
printf("%c%c", one, one);
return;
case 1:
printf("%c", one);
return;
default:
return;
}
}
留言列表