Question: #include int get_value(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case

#include
int get_value(char c) {
switch (c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}
int roman_to_decimal(char *roman) {
int decimal = 0;
int prev = 0;
for (int i = 0; roman[i] != '\0'; i++) {
int current = get_value(roman[i]);
if (current == -1) {
return -1;
}
if (current > prev) {
decimal += current - 2 * prev;
} else {
decimal += current;
}
prev = current;
}
return decimal;
}
int main() {
char roman[100];
int decimal;
printf("Enter a Roman numeral: ");
scanf("%s", roman);
decimal = roman_to_decimal(roman);
if (decimal == -1) {
printf("Invalid Roman numeral ");
} else {
printf("Decimal equivalent: %d ", decimal);
}
return 0;
}
/////
#include
int roman_to_decimal(char *roman) {
int decimal = 0;
int prev = 0;
for (int i = 0; roman[i] != '\0'; i++) {
int current = 0;
switch (roman[i]) {
case 'I': current = 1; break;
case 'V': current = 5; break;
case 'X': current = 10; break;
case 'L': current = 50; break;
case 'C': current = 100; break;
case 'D': current = 500; break;
case 'M': current = 1000; break;
default: return -1;
}
if (current > prev) {
decimal += current - 2 * prev;
} else {
decimal += current;
}
prev = current;
}
return decimal;
}
int main() {
char roman[100];
int decimal;
printf("Enter a Roman numeral: ");
scanf("%s", roman);
decimal = roman_to_decimal(roman);
if (decimal == -1) {
printf("Invalid Roman numeral ");
} else {
printf("Decimal equivalent: %d ", decimal);
}
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!