60 595
Assignments Done
97,8%
Successfully Done
In April 2018

Answer to Question #25461 in C++ for hanrik

Question #25461
Write a C program that converts a string representing a number in Roman numeral form to decimal form. The symbols used in the Roman numeral system and their equivalents are given below:



I 1

V 5

X 10

L 50

C 100

D 500

M 1000



For example, the following are roman numbers: XII (12), CII(102), XL (40). The rules for converting a roman number to decimal is as follows:



a. Set the value of the decimal number to zero.

b. Scan the string containing the roman character fro left to right. If the character is not one of the symbols in the numeral symbol set, the program must print an error message and terminate. Otherwise, continue with the following steps:

If the next character is a null character(if the current character is the last character) add the value of the current character to the decimal value.
If the value of the current character is greater than or equal to the value of the next character, add the value of the current character to the de
Expert's answer
#include <stdio.h>
#include <string.h>

const char symbols[7] = "IVXLCDM";
const short values[7] = { 1, 5, 10, 50, 100, 500, 1000 };

int roman_to_decimal(const char* number)
{
int result = 0;
char* symbol;
int value, nextValue;

int s;
for (s = 0; s < strlen(number); s++)
{
symbol = strchr(symbols, number[s]);
if (symbol == 0)
{
printf("'%c' is not a Roman numeral system symbol\n", number[s]);
return -1;
}
value = values[(int)(symbol - symbols)];

if (number[s + 1] == '\0')
result += value;
else
{
symbol = strchr(symbols, number[s + 1]);
nextValue = values[(int)(symbol - symbols)];

if (value >= nextValue)
result += value;
else
result -= value;
}

}
return result;
}

int main()
{
printf("XII = %d\n", roman_to_decimal("XII"));
printf("IX = %d\n", roman_to_decimal("IX"));
printf("CII = %d\n", roman_to_decimal("CII"));
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions