• 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

    • Kindle Scribe Essentials Bundle offers great value for students and professionals by Paul Hill Earlier this week, we featured the Kindle Scribe in a deals post. Amazon’s largest Kindle had fallen to its lowest price; these are still on offer if you’re interested. Now, the company has also decided to discount the Kindle Scribe Essentials Bundle, which includes the Kindle Scribe with Premium Pen, premium leather folio, and a 9W power adapter. The Premium Pen is already included with the Kindle Scribe, but this bundle adds the premium leather folio and 9W power adapter. The 64GB Kindle Scribe variants (available in two colors) cost $404.97, down from $569.97. By using this deal, you’re saving $165 off the list price and it’s $65 less than if you bought the bundle items separately. In the original deal, which is still available, you got the Kindle and the pen, so this bundle adds the 9W power adapter and the premium leather folio. If you are still looking for Father’s Day gifts, this Kindle Scribe Essentials Bundle will not arrive in time, even if you get a Prime member trial. What the Kindle Scribe does The Kindle Scribe features a large 10.2-inch glare-free display with a 300 ppi density. It comes with a Premium Pen that makes it feel like you’re writing on paper as you jot down your notes. To make writing easier, you get Active Canvas for in-book notes and a built-in notebook with templates. You can import and write on PDFs and documents via Send to Kindle, including sending directly from Word if you have a Microsoft 365 subscription. With the inclusion of the natural leather folio, which patinas over time, you are able to wake and sleep your Kindle Scribe by opening and closing the folio. It uses a magnetic attachment to ensure a secure close. Once you have written out your notes, the Kindle Scribe allows you to summarize them using artificial intelligence. You can even customize the length and tone of your notes. You can also refine your notes by converting your handwritten words into a script font. One of the standout features of other Kindle devices is their spectacular battery life, and the Kindle Scribe promises the same. The battery will last you up to 12 weeks for reading and up to 3 weeks for writing. Furthermore, Amazon has used 18% recycled materials including 100% recycled aluminum parts, and it comes in fully recyclable packaging. Finally, and it shouldn’t really need mentioning, the Kindle Scribe has full access to the Kindle Store so you can quickly and easily gain access to all of the latest books. Should you buy it? Anyone who has ever loved using a Kindle product should check out the Scribe as it has many of the same characteristics, but on a bigger scale and with writing capabilities. Students at college, especially those studying something like literature, could benefit. It could also be good for professionals who need to annotate documents. If you saw the deal earlier this week and were worried about scuffing up the device, then this deal may be more tempting thanks to the inclusion of the folio case. Amazon Kindle Scribe Essentials Bundle (16GB): $359.97 (Amazon US) / MSRP $519.97 Amazon Kindle Scribe Essentials Bundle (32GB): $374.97 (Amazon US) / MSRP $539.97 Amazon Kindle Scribe Essentials Bundle (64GB, Tungsten/Black Folio): $404.97 (Amazon US) / MSRP $569.97 Amazon Kindle Scribe Essentials Bundle (64GB, Metallic Jade/Dark Emerald Folio): $404.97 (Amazon US) / MSRP $569.97 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.
    • sounds like this same jet had electrical failures in a prior flight including the entertainment systems, and call buttons and other things not working
    • That's the publisher's fault and happens with or without GamePass. Microsoft at least offers the Play Anywhere option.
    • Windows Phone actually had some great features, the problem Microsoft had is that developers are not used to having to deal with stores etc. and they couldn't get them onboard. But there were a lot of good features, in fact we see more and more of them popping up on other OS' all the time.
  • Recent Achievements

    • First Post
      NeoToad777 earned a badge
      First Post
    • Week One Done
      JoeV earned a badge
      Week One Done
    • One Month Later
      VAT Services in UAE earned a badge
      One Month Later
    • First Post
      LsDmT earned a badge
      First Post
    • Week One Done
      evershinefacilityservice earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      572
    2. 2
      ATLien_0
      247
    3. 3
      +Edouard
      162
    4. 4
      +FloatingFatMan
      151
    5. 5
      Michael Scrip
      113
  • Tell a friend

    Love Neowin? Tell a friend!