We would like to write a function that will read the next number in the input in roman numerals, and return it as an integer. We will also write a driver program to test this function.
Unfortunately, C does not provide a "%R" conversion specifier, or anything like that, so we will have to write our own. The function will be similar to getchar(), in that it is given nothing and returns the next number in the input as an integer.
As before, we need to design the overall program. We start with the five step process.
What is this program supposed to do?
The program is supposed to read the next roman number from the input. The main objective is to write the function get_roman(), but we will also need a driver to test it.
What kind of information is it given? (What is the input?)
The number is to be read from the standard input, and consists of roman digits:
M = 1000
D = 500
C = 100
L = 50
X = 10
V = 5
I = 1
What kind of results is it to produce? (What is the output?)
The function should return the integer representaion of the roman number. The driver should just print the result.
What formulas or techniques will be needed?
At first, the method seems straightforward; we just add up the values associated with each roman digit. However, roman numbers have an added twist - prefix digits. If a digit with a lower value preceeds a digit with a larger value, the lower value should be subtract rather than added.
As an example, let's try the roman number representation of this year:
M C M X C V
We process the number from left to right:
M C M X C V
1000
M C M X C V
1000 + 100 = 1100
M C M X C V
1100 - 100 + ( 1000 - 100 ) = 1900
undo
M C M X C V
1900 + 10 = 1910
M C M X C V
1910 - 10 + ( 100 - 10 ) = 1990
undo
M C M X C V
1990 + 5 = 1995
The Driver Algorithm:
get the first number in roman numerals
While there are more numbers
print the number
get the next number in roman numerals
The Roman Module Algorithm:
Given: nothing
Returns: an integer, converted from the input or EOF
initialize previous digit
get the first digit
while we still have roman digits
convert digit to its value
if previous digit was a prefix
adjust the total
otherwise accumulate the total
save this digit as previous
get the next digit
return the number of EOF
The Roman Utilities and their Algorithms are a bit more involved and are shown here.
The code is shown in the Code for Lecture section under Roman.