• 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){}
        }
    }
}

Link to comment
Share on other sites

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
Link to comment
Share on other sites

  • 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..

Link to comment
Share on other sites

  • 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.

Link to comment
Share on other sites

  • 0

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.
Link to comment
Share on other sites

  • 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.

Link to comment
Share on other sites

  • 0

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.
Link to comment
Share on other sites

  • 0

*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.

Link to comment
Share on other sites

  • 0

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.
Link to comment
Share on other sites

  • 0

"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.

Link to comment
Share on other sites

  • 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

Link to comment
Share on other sites

  • 0

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.

Link to comment
Share on other sites

  • 0

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
Link to comment
Share on other sites

  • 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
Link to comment
Share on other sites

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

    • No registered users viewing this page.