1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
#include "roman.h"
#include <iostream>
using namespace std;
//default constructor
roman::roman()
{
numeral = "";
}
//non-default constructor
roman::roman(string num)
{
numeral = num;
}
roman::roman(int decNum)
{
int t=0, h=0, ten=0, o=0;
string thousand [5] = { "", "M", "MM", "MMM", "MMMM"};
string hundred [10] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
string tens [10]= {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
string ones [10] = {"", "I" ,"II","III","IV","V","VI","VII","VIII","IX"};
t = decNum % 1000;
decNum -= t * 1000;
h = decNum % 100;
decNum -= h *100;
ten = decNum % 10;
decNum -= ten * 10;
o = decNum % 1;
numeral = thousand[t] + hundred[h] + tens[ten] + ones[o];
}
bool roman::setNumeral(string num)
{
numeral = num;
return true;
}
string roman::getNumeral()
{
return numeral;
}
int roman::toInt()
{
int sum = 0, prev = 1000;
string tempNum = numeral;
for(int i = 0; i < tempNum.length(); i++)
{
switch (numeral[i])
{
case 'M':
sum += 1000;
if(prev < 1000)
sum -= 2 * prev;
prev = 1000;
break;
case 'D':
sum += 500;
if(prev < 500)
sum -= 2 * prev;
prev = 500;
break;
case 'C':
sum += 100;
if(prev < 100)
sum -= 2 * prev;
prev = 100;
break;
case 'L':
sum += 50;
if(prev < 50)
sum -= 2 * prev;
prev = 50;
break;
case 'X':
sum += 10;
if(prev < 10)
sum -= 2 * prev;
prev = 10;
break;
case 'V':
sum += 5;
if(prev < 5)
sum -= 2 * prev;
prev = 5;
break;
case 'I':
sum += 1;
prev = 1;
break;
}
}
return sum;
}
void roman::print()
{
cout << " " << numeral;
}
|