Roman numbers to natural numbers

I am supposed to make a program that does as the title says.
Each roman number ends with a -> .

I have made a code that I expected should work and I have no idea why it doesn't. Basically my code, seems to ignore substraction of roman numbers here is an example:

INPUT: IX.
OUTPUT: 11 (Incorrect, correct output should be 9)

Steps I expected program would do

READ I
roman_number = I
result = 0 + 1 = 1
previous = I

READ X
roman_number = X
result = 1 + 8 = 9
previous = X

READ .
roman_number = .
result = 9 (output 9)
previous = .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;

int main () {
	char roman_numbers;
	char previous;
	int result = 0;
	while (cin >> roman_numbers) {
		if (roman_numbers == 'M') {
			if (previous == 'C') result += 800;
			else result += 1000;
		}
		if (roman_numbers == 'D') {
			if (previous == 'C') result += 300;
			else result += 500;
		}
		if (roman_numbers == 'C') {
			if (previous == 'X') result += 80;
			else result += 100;
		}
		if (roman_numbers == 'L') {
			if (previous == 'X') result += 30;
			else result += 50;
		}
		if (roman_numbers == 'X') {
			if (previous == 'I') result += 8;
			else result += 10;
		}
		if (roman_numbers == 'V') {
			if (previous == 'I') result += 3;
			else result += 5;
		}
		if (roman_numbers == 'I') result += 1;
		if (roman_numbers == '.') {
			cout << result << endl;
			result = 0;
		}	
		char previous = roman_numbers;
	}
}
Last edited on
Made it to work, have been looking for like half an hour to finally see that program wasn't working because had to write "previous = roman_numbers;" instead of "char previous = roman_numbers;"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;

int main () {
	char roman_numbers;
	char previous;
	int result = 0;
	while (cin >> roman_numbers) {
		if (roman_numbers == 'M') {
			if (previous == 'C') result += 800;
			else result += 1000;
		}
		if (roman_numbers == 'D') {
			if (previous == 'C') result += 300;
			else result += 500;
		}
		if (roman_numbers == 'C') {
			if (previous == 'X') result += 80;
			else result += 100;
		}
		if (roman_numbers == 'L') {
			if (previous == 'X') result += 30;
			else result += 50;
		}
		if (roman_numbers == 'X') {
			if (previous == 'I') result += 8;
			else result += 10;
		}
		if (roman_numbers == 'V') {
			if (previous == 'I') result += 3;
			else result += 5;
		}
		if (roman_numbers == 'I') result += 1;
		if (roman_numbers == '.') {
			cout << " = " << result << endl;
			result = 0;
		}
		else cout << roman_numbers;
		previous = roman_numbers;
	}
}
Topic archived. No new replies allowed.