Saturday, 12 November 2016

Q)Write a program that converts a number entered in Roman numerals to decimal. Your program should consist of a class, say, romanType. An object of type romanType should do the following:  Store the number as a Roman numeral.  Convert and store the number into decimal form.  Print the number as a Roman numeral or decimal number as requested by the user. The decimal values of the Roman numerals are:
 Test your program using the following Roman numerals: MCXIV, CCCLIX, MDCLXVI.

#include<iostream>
using namespace std;

class romanType{
      char R[8]; //intialized by the constructor
      int decimal; //stores the decimal number after converting
public:
      romanType(); //constructor
      void R2D(); //declaration of a function to convert roman into decimal
      int get_decimal();//declaration of a function to get decimal number
    bool operator>=(int);//operator overloading
     
};
int main()
{
      romanType ob; //creating the object
      ob.R2D();
      if (ob >= 0)
            cout << "Decimal : " << ob.get_decimal() << endl;
      else
            cout << "Invalid Format of a number" << endl;

}
void romanType::R2D()
{
      char a[1000];
      cout << "Enter the number in roman format(M-D-C-L-X-V-I) :";
      cin >> a;
      int dec,l,n=0;
      l = strlen(a); //cal the length of char string
      for (int i = l-1; i>=0; i--) //cal from roman to decimal format
      {
            a[i] = toupper(a[i]);
            if (a[i] == R[0])
                  dec = 1000;
            else if (a[i] == R[1])
                  dec = 500;
            else if (a[i] == R[2])
                  dec = 100;
            else if (a[i] == R[3])
                  dec = 50;
            else if (a[i] == R[4])
                  dec = 10;
            else if (a[i] == R[5])
                  dec = 5;
            else if (a[i] == R[6])
                  dec = 1;
            else
            {
                  decimal = -1;
                  break;     
            }
            if (n > dec)
                  decimal = (decimal-dec);
            else
                  decimal = decimal + dec;     
            n = dec;
      }
}
int romanType::get_decimal() //function to return the decmial number
{
      return decimal;
}
romanType::romanType()//Constructor
{
      R[0] = 'M';
      R[1] = 'D';
      R[2] = 'C';
      R[3] = 'L';
      R[4] = 'X';
      R[5] = 'V';
      R[6] = 'I';

      decimal = 0;
}
bool romanType::operator>=(int n = 0)
{
      if (decimal >= 0)
            return 1;
      else
            return 0;
}


No comments:

Post a Comment