• 0

[C#] Convert Roman Numerals to Decimal/Integer


Question

Good day/eve to all members here in Neowin.net

 

I need a help on this matter, and here is the question

 

 

"Write a program that converts a number entered in Roman Numerals to decimal/integer. Your program should consist a class, say Roman. An object of type should do the following:"

 

  • Store the number as a Roman numeral

  • Convert and store the number into decimal

  • Print the number as a Roman numeral or decimal number as requested by the user.


The decimal values of the Roman numerals are:

  • M     1000

  • D       500

  • C       100

  • L         50

  • X         10

  • V           5

  • I             1


Test your program using the following Roman Numerals: MCXIV, CCLIX and MDCLXVI

 

and here is my code:

 

I already have the code downloaded in the internet and I edit it

 

Note: I did not create a class yet.

 

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(" enter roman numerals: ");
            String rom = Console.ReadLine();
            //int length=[ ];
            int dc;
            //decimal dc=length;
            //int rom[length];
            //int length =length;

            int i;
            try
            {
                for (i = 0; i < 10; i++)
                {
                    switch (rom[i])
                    {
                        case 'M':
                        case 'm':
                            dc = 1000;
                            //if (dc < dc)
                            //{
                            //    dc -= dc;
                            //    Console.WriteLine(dc);
                            //}
                            //else
                            //{
                            //    dc += dc;
                            //    Console.WriteLine(dc);
                            //}
                            Console.WriteLine(dc);
                            break;
                        case 'D':
                        case 'd':
                            dc = 500;
                            Console.WriteLine(dc);
                            break;
                        case 'C':
                        case 'c':
                            dc = 100;
                            Console.WriteLine(dc);
                            break;
                        case 'L':
                        case 'l':
                            dc = 50;
                            Console.WriteLine(dc);
                            break;
                        case 'X':
                        case 'x':
                            dc = 10;
                            Console.WriteLine(dc);
                            break;
                        case 'V':
                        case 'v':
                            dc = 5;
                            Console.WriteLine(dc);
                            break;
                        case 'I':
                        case 'i':
                            dc = 1;
                            Console.WriteLine(dc);
                            break;
                        //default:
                        //Console.Write("error
                    }

                }

            }
            catch (IndexOutOfRangeException e){}
        }
    }
}

16 answers to this question

Recommended Posts

  • 0

All I know

public static RomanNumber operator +(RomanNumber n1, RomanNumber n2)
{
   if (n1.value == "Rocky V" && n2.value == "Rocky II")
       return new RomanNumber("Rocky VII: Adrian's Revenge");
   else
       throw new NotImplementedException();
}
  • Like 1
  • 0

class RomanApp {
	static void Main ( string[] args ) 
	{
		Console.WriteLine ( "Please enter a roman numeral" );
		
		Roman numeral = new Roman ( Console.ReadLine() );
		Console.WriteLine ( "You entered the roman numeral {0} which equals {1} in the decimal system.", numeral.ToNum(), numeral.ToDec() );
	}
}

class Roman {

	private const int M = 1000;     /* milium / mille */
	private const int D = 500;	/* quingenti */
	private const int C = 100;	/* centum */
	private const int L = 50;	/* quinquaginta */
	private const int X = 10;	/* decem */
	private const int V = 5;	/* quinque */
	private const int I = 1;	/* unus */
	
	private string num; 		/* roman numeral */
	private int    dec; 		/* decimal equivalent */
	
	public Roman ( ) {
	
	}
	
	public Roman ( string numeral ) {
		Store ( numeral );
	}
	
	private Store ( string numeral ) {
		this.num = numeral;
		this.dec = NumeralToDec ( numeral );
	}

	private int NumeralToDec ( string numeral ) {
		int count       = 0;
		int dec, last 	= 0;
		
		for ( int i = 0; i < numeral.Length ; i++ ) {
			dec = CharToDec ( numeral [ i ] );
			if ( last && last < dec ) {
			     /*	subtraction must be power of ten in roman numerals ( I, X, or C ) 
				should probably throw exception here instead of assert.
			     */
			     assert ( last == 1 || last % 10 == 0 );
			     count -= last * 2;
			}
			
			count += dec;
			last  = dec;
		}	
	}
	
	private string DecToNumeral ( int dec ) {
		string num;
		int millia = 0, quingenti = 0, cententa = 0, quinquaginta = 0, decem = 0, quinque = 0, uni = 0;
		
		if ( dec > M )
			millia = dec / M;			
		dec -= millia;
		
		if ( dec > D ) 
			quingenti = dec / D;
		dec -= quingenti;
		
		if ( dec > C )
			cententa = dec / C
		dec -= cententa;
		
		if ( dec > L )
			quinquaginta = dec / L;
		dec -= quinquaginta;
		
		if ( dec > X )
			decem = dec / X;
		dec -= decem;
		
		if ( dec > V )
			quinque = dec / V;
		dec -= quinque;
		
		if ( dec > I )
			uni = dec / I;
		dec -= uni;
		
		/* todo: take into account subtractions and construct string. */
		
		return num;
	}
	
	private int CharToDec ( char numeral ) {
		int dec;
		
		switch ( numeral ) {
		case 'M':
		case 'm':
			dec = M;
			break;
		case 'D':
		case 'd':
			dec = D;
			break;
		case 'C':
		case 'c':
			dec = C;
			break;
		case 'L':
		case 'l':
			dec = L;
			break;
		case 'X':
		case 'x':
			dec = X;
			break;
		case 'V':
		case 'v':
			dec = V;
			break;
		case 'I':
		case 'i':
			dec = I;
			break;
		default:
			/* todo: unrecognised roman numeral - raise exception */
			assert ( false );
		}

		return dec;
	}
	
	public Roman operator = ( string numeral ) {
		Store ( numeral );
		return this;
    }

	public Roman operator += ( string numeral ) {
		this.dec += NumeralToDec ( numeral );
		this.num = DecToNumeral ( this.dec );
		return this;
    }

	public int	ToDec ( ) { return dec; }
	public string 	ToNum ( ) { return num; }
}

Something like this I would imagine.

Note: don't rely on this code as I neither compiled or tested it. I'm not even running Windows so..

  • 0

http://jsfiddle.net/mjnqtotb/2/

 

Decimal to roman converter I just made because I was bored, you need to do it the other way around which isn't hard either  :p

 

Use following for dec to rom: http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm

and this for rom to dec: http://www.rapidtables.com/convert/number/how-roman-numerals-to-number.htm

 

Above 2 links show the easiest logic to do the job ;)

 

I'll change my code into 2 functions since I'm bored for rom to dec and dec to rom.

Posting link in a sec, keep in mind this is not C but JS.

  • 0
  On 09/09/2014 at 13:28, simplezz said:

Note: don't rely on this code as I neither compiled or tested it. I'm not even running Windows so..

The platform works on all OS's (desktop and mobile), don't need to be running Windows.
  • 0

Now here we go: http://jsfiddle.net/mjnqtotb/8/

 

The JS code:

var roman = [[1000,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]];

function torom() {
    var rom = "";
    var dec = document.getElementById("number").value;
    for(x=0;x<roman.length;x++) {
        if(roman[x][0] <= dec) {
            rom += roman[x][1];   
            dec -= roman[x][0];
            x = -1; //Reset loop
        }
    }
    alert("Roman: "+rom);
}
function todec() {
    var dec = 0;
    var rom = document.getElementById("number").value;
    for(x=0;x<roman.length;x++) {
        if(rom.substring(0, roman[x][1].length) == roman[x][1]) {
            rom = rom.substring(roman[x][1].length);
            dec += roman[x][0];
            x = -1; //Reset loop
        }
    }
    alert("Decimal: "+dec);
}

Using an array with arrays for roman numbers and their decimal values is a simple method when you combine it with a for loop.

  • 0
  On 09/09/2014 at 14:06, simplezz said:

Yeah I'm not going to install mono junk on my nice Arch box ;)

*shrug* Do as you will, just mentioning it for people who are posting code without actually knowing if it works who might not know that the thing is open source and freely available for everything.
  • 0
  On 09/09/2014 at 14:09, Max Norris said:

*shrug* Do as you will, just mentioning it for people who are posting code without actually knowing if it works who might not know that the thing is open source and freely available for everything.

I wouldn't recommend that as Mono is sufficiently different to Microsoft's implementation that things might not work the same or even compile successfully. Best to stick to Windows if doing dotnet/C# stuff IMO. If someone wants reliable cross platform development, Python and Java are more suitable and better supported.

  • 0
  On 09/09/2014 at 14:17, simplezz said:

I wouldn't recommend that as Mono is sufficiently different to Microsoft's implementation that things might not work the same or even compile successfully. Best to stick to Windows if doing dotnet/C# stuff IMO. If someone wants reliable cross platform development, Python and Java are more suitable and better supported.

Seeing as you've apparently never even tried it as you don't want that "junk" on your system, and I have, I can tell you that's quite untrue. The main stumbling block is calling system specific stuff. (Just like any other language.) But I didn't mention that to start yet another lame OS flame war.
  • 0
  On 09/09/2014 at 04:00, Gil37 said:

"Write a program that converts a number entered in Roman Numerals to decimal/integer. Your program should consist a class, say Roman. An object of type should do the following:"

 

<snip>

Test your program using the following Roman Numerals: MCXIV, CCLIX and MDCLXVI

 

and here is my code:

 

I already have the code downloaded in the internet and I edit it

 

Note: I did not create a class yet.

 

<snip>

 

So you're clearly cheating on a piece of homework assignment!?!?

 

As you can see, I was about to have a little go at you about cheating, but looking at the code you've "downloaded" and edited, there's very little to it, so meh.

 

However, I agree with Eric on this one; While I can and do offer a lot of help to people in this forum who need it (as you can see going back through my post history), I'm not going to just do your assignment for you. If you want some help, you need to actually ask some questions, or tell me precisely what problems you have so I can point you towards a solution.

  • 0

I've already posted the logic behind the code above in another language with links for explanation, I think he will be able to do the assignment from there.

 

The trick is in the following numbers: 90040090409 and 4 because those numbers are not made by adding a roman symbol after a roman symbol but by adding a roman symbol before a roman symbol. This is something that most tutorials and websites forget on the internet when talking about roman numbers.

 

So if you do not include those numbers also in your code your program will not work correctly because it will use incorrect roman symbols in some cases like: 1900, 992, 96, 473, 9, 94, 49 etc

  • 0
  On 09/09/2014 at 14:24, Max Norris said:

Seeing as you've apparently never even tried it as you don't want that "junk" on your system, and I have, I can tell you that's quite untrue. The main stumbling block is calling system specific stuff. (Just like any other language.) But I didn't mention that to start yet another lame OS flame war.

I have tried it before. That's why I don't want it on my system again ;) And yes, as I said, things might not work the same across systems. That's why I don't recommend it. I don't want to detract further from the purpose of this thread so let's leave it at that.

  • 0
  On 09/09/2014 at 14:08, Seahorsepip said:

The JS code:

var roman = [[1000,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]];
Using an array with arrays for roman numbers and their decimal values is a simple method when you combine it with a for loop.
I like the idea of using a table for the conversion from an integer to roman numeral. I've updated my code to use something similar:

class RomanApp {
	static void Main ( string[] args ) 
	{
		Console.WriteLine ( "Please enter a roman numeral" );
		
		Roman numeral = new Roman ( Console.ReadLine() );
		Console.WriteLine ( "You entered the roman numeral {0} which equals {1} in the decimal system.", numeral.ToNum(), numeral.ToDec() );
	}
}

class Roman {
	
	private const int M = 1000;	/* milium / mille */
	private const int D = 500;	/* quingenti */
	private const int C = 100;	/* centum */
	private const int L = 50;	/* quinquaginta */
	private const int X = 10;	/* decem */
	private const int V = 5;	/* quinque */
	private const int I = 1;	/* unus */
	
	private string num; 		/* roman numeral */
	private int    dec; 		/* decimal equivalent */
	
	public Roman ( ) {
	
	}
	
	public Roman ( string numeral ) {
		StoreNum ( numeral );
	}
	
	public Roman ( int dec ) {
		StoreDec ( numeral );
	}

	private StoreNum ( string numeral ) {
		this.num = numeral;
		this.dec = NumeralToDec ( numeral );
	}

        private StoreDec ( int dec ) {
		this.dec = dec;
		this.num = DecToNumeral ( dec );
	}
        
        private int NumeralToDec ( string numeral ) {
		int count 	= 0;
		int dec, last 	= 0;
		
		for ( int i = 0; i < numeral.Length ; i++ ) {

			dec = CharToDec ( numeral [ i ] );
			if ( last && last < dec ) {
				assert ( last == I || last == X || last == C );
				count -= last * 2;
			}
			
			count += dec;
			last  = dec;
		}	
	}
	
	private string DecToNumeral ( int dec ) {
		
		struct NumeralPair {
			public int 	value;
			public string	roman;
		};
	
		NumeralPair[] PairTable = new NumeralPair[] {
			{ M, "M" }, { M-C, "CM"}, { D, "D"}, { D-C, "CD" }, { C, "C" }, { C-X, "XC" }, 
			{ L, "L" }, { L-X, "XL" }, { X, "X" }, { X-I, "IX" }, { "V" }, { V-I, "IV" }, { I, "I" }
		};

		string numeral;
		for each ( NumeralPair pair in PairTable ) {
		
			while ( dec >= pair.value ) {
				numeral += pair.roman;
				dec 	-= pair.value;
			}
		}
		
		return numeral;
	}
	
	private int CharToDec ( char numeral ) {
		int dec;
		
		switch ( numeral ) {
		case 'M':
		case 'm':
			dec = M;
			break;
		case 'D':
		case 'd':
			dec = D;
			break;
		case 'C':
		case 'c':
			dec = C;
			break;
		case 'L':
		case 'l':
			dec = L;
			break;
		case 'X':
		case 'x':
			dec = X;
			break;
		case 'V':
		case 'v':
			dec = V;
			break;
		case 'I':
		case 'i':
			dec = I;
			break;
		default:
			/* todo: unrecognised roman numeral - raise exception */
			assert ( false );
		}

		return dec;
	}
	
	public Roman operator = ( string numeral ) {
		StoreNum ( numeral );
		return this;
	}

	public Roman operator += ( string numeral ) {
                StoreDec ( this.dec + NumeralToDec ( numeral ) );
		return this;
	}

	public int	ToDec ( ) { return dec; }
	public string	ToNum ( ) { return num; }
}
  • Like 1
  • 0

So... are you having difficulty figuring out the algorithms, or is it about translating the algorithms into C#? You need to be more precise than: "I have this problem that I must solve in C# and I don't know how, please help".

 

I'm closing this thread, please read our guidelines on asking help for homework as you've already been pointed to by other members, and create a new thread with a real question when you have one.

  • Like 2
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Ha! Just as i was mentioning here yesterday that it was weird that MS hadn't announced any 25H2! Hope it includes some more bells and whistles.
    • 65-inch Hisense U8 Series Google Smart TV drops to its lowest price by Fiza Ali Amazon US is currently offering the 65-inch Hisense U8 Series Google Smart TV at its lowest price to date. So, if you are thinking of upgrading your home entertainment system, you may want to check it out. The Hisense U8 uses Mini‑LED Pro backlighting with Full Array Local Dimming to deliver up to 5,000 nits of peak brightness. Its QLED Colour system employs quantum dots to render over a billion shades, while Dolby Vision IQ, HDR10+, HDR10, HLG and Advanced HDR by Technicolor formats ensure a wide dynamic range and accurate colour reproduction. A native 165Hz refresh rate combined with a Variable Refresh Rate (VRR) of 48Hz to 165Hzthanks to AMD FreeSync Premium Pro, and Low‑Latency MEMC (Motion enhancement and compensation) eliminate screen tearing and input lag. The Anti‑Glare Low Reflection Pro coating reduces reflections from ambient light. Furthermore, audio is handled by a 72W 4.1.2 channel system featuring Dolby Atmos, with four primary and surround speakers, two up‑firing height channels and a built‑in subwoofer. Powered by the Hi‑View AI Engine Pro, the U8 Series automatically analyses and optimises picture and sound according to the content on screen. Moreover, Google TV provides a full smart platform with Google Assistant built in, compatibility with Alexa, access to apps, and voice control. Finally, connectivity options include Wi‑Fi 6E, Bluetooth 5.3, three HDMI 2.1 ports (one with eARC), two USB ports (one USB 3.0, one USB 2.0), optical digital audio output, RF antenna input (NTSC/Clear QAM/ATSC 3.0), composite video and L/R audio inputs, and an Ethernet LAN port. 65-inch Hisense U8 Series Google Smart TV: $1,242.87 (Amazon US) - 44% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • Unless you have bought a CoPilot+ laptop or tablet with a Snapdragon AI processor, Recall is not installed.
    • Teams is a happiness sucking piece of software design to make life horrible for those who use it. I am so glad I only use it once a week.
  • Recent Achievements

    • Week One Done
      Alexander 001 earned a badge
      Week One Done
    • Week One Done
      icecreamconesleeves earned a badge
      Week One Done
    • One Year In
      PAC0 earned a badge
      One Year In
    • One Month Later
      PAC0 earned a badge
      One Month Later
    • One Year In
      Shahmir Shoaib earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      564
    2. 2
      +FloatingFatMan
      189
    3. 3
      ATLien_0
      185
    4. 4
      Skyfrog
      113
    5. 5
      Som
      109
  • Tell a friend

    Love Neowin? Tell a friend!