Hi,
I have written a code for Roman Numeral basic mathematical operation in C++. How to do unit testing for it/ How to write unit testing program for it?
Here is the code:
#include <iostream>
#include <string>
using namespace std;
//Function to convert decimal number to roman
string decimal_to_Roman(int number)
{
string roman = "";
while (number > 0)
{
if (number >= 1000)
{
roman += "M";
number -= 1000;
}
else if (number >= 500)
{
roman += "D";
number -= 500;
}
else if (number >= 100)
{
roman += "C";
number -= 100;
}
else if (number >= 50)
{
roman += "L";
number -= 50;
}
else if (number >= 10)
{
roman += "X";
number -= 10;
}
else if (number >= 5)
{
roman += "V";
number -= 5;
}
else
{
roman += "I";
number -= 1;
}
}
return roman;
}
//Function to convert roman number to decimal
int roman_to_decimal(string roman)
{
int number = 0;
for (int i = 0; i<roman.length(); i++)
{
switch (roman[i])
{
case 'M':
number += 1000;
break;
case 'D':
number += 500;
break;
case 'C':
number += 100;
break;
case 'L':
number += 50;
break;
case 'X':
number += 10;
break;
case 'V':
number += 5;
break;
case 'I':
number += 1;
break;
default:
cout << "Data error\n";
}
}
return number;
}
//Function to perform mathematical operations(+,-,*,/)
int calculator(int n1, int n2, char opr)
{
switch (opr)
{
case '+':
return n1 + n2;
break;
case '-':
return n1 - n2;
break;
case '*':
return n1*n2;
break;
case '/':
if (n2 != 0)
{
return n1 / n2;
}
else
break;
}
return 0;
}
//Function to print result
void result(string r1, string r2, char opr, string r)
{
cout << r1 << endl;
cout << opr << endl;
cout << r2 << endl;
cout << r << endl;
}
int main()
{
string r1, r2, r;
char opr;
int n1, n2, n;
cin >> r1;
n1 = roman_to_decimal(r1);
cin >> opr;
cin >> r2;
n2 = roman_to_decimal(r2);
n = calculator(n1, n2, opr);
r = decimal_to_Roman(n);
result(r1, r2, opr, r);
}