Sum Issue
Aug 27, 2016 at 1:39am UTC
Hello I am working on a roman number to decimal program. My code works a bit for example when I type MIII my output is 1003, but then I type MX I get 10. Any reason why this happening?
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 42 43 44 45 46 47 48 49 50
#include<iostream>
#include<string>
using namespace std;
int main() {
string roman;
int sum;
int decimal = 0;
cout << "Please enter a Roman Numeral to convert: " ;
cin >> roman;
for (int i=0; i<roman.length(); i++)
{
switch (roman[i])
{
case 'M' :
decimal = 1000;
break ;
case 'D' :
decimal = 500;
sum = decimal;
break ;
case 'L' :
decimal = 50;
break ;
case 'X' :
decimal = 10;
break ;
case 'V' :
decimal = 5;
break ;
case 'I' :
decimal ++;
break ;
}
}
cout << decimal << endl;
}
Aug 27, 2016 at 2:20am UTC
In all of your cases except for the 'I' case you are assigning a new value to decimal, you should be adding the value:
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 42 43 44 45 46 47 48
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a Roman Numeral to convert: " ;
string roman;
cin >> roman;
int decimal = 0;
for (unsigned int i = 0; i < roman.length(); i++)
{
switch (roman[i])
{
case 'M' :
decimal += 1000;
break ;
case 'D' :
decimal += 500;
break ;
case 'C' :
decimal += 100;
break ;
case 'L' :
decimal += 50;
break ;
case 'X' :
decimal += 10;
break ;
case 'V' :
decimal += 5;
break ;
case 'I' :
decimal++;
break ;
}
}
cout << decimal << endl;
}
Please enter a Roman Numeral to convert: MXVI
1016
Aug 27, 2016 at 2:32am UTC
You are a Life Saver! Thank Thank You so Much
Topic archived. No new replies allowed.