Answered step by step
Verified Expert Solution
Question
1 Approved Answer
#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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started