Normally, I can do Roman numerals in my head or on paper in a second or two. Some of my students were probably less familiar with them at this point. Either way, the process of breaking down the rules for the conversion in a way that could be put into code was an interesting one.
I really wanted to do this from scratch, though, so I did and it was more fun. One challenge was determining the correct subtractive letter at each point. I came up with this:. Subtract the result from the current number being used.
This means that if the number being subtracted by the input value is , it will divide by 10 and get Writing the smaller number to the left of the larger number in the Roman system represents subtraction.
In the above program, we have included string. The program first checks for the validity of the roman number entered by the user using two consecutive if conditions as discussed in the rule above. If the entered roman number is valid then only third if condition computes the equivalent decimal number.
For example, if the input is 54,, the code separates it into the pieces 54 and It calculates the number of thousands in the value, uses that number as an index into the ThouLetters array, and adds the corresponding array value to the result string. When it finishes, it simply returns the result. When you enter a value in either of the two upper text boxes and click Convert, the program converts your value into the other format and then converts the result back into the original format.
The program works quite well for the most obvious cases and handles many odd cases. C Helper. Skip to content. Roman to Arabic The program uses the following code to convert a string containing Roman numerals into an integer.
Add 'I', 1 ; CharValues. Add 'V', 5 ; CharValues. Add 'X', 10 ; CharValues. Add 'L', 50 ; CharValues. Add 'C', ; CharValues.
0コメント