I need to convert roman numerals to integer values, order does not matter. (9=VIIII)
In the present I start to get a fudge factor from my code, it starts at 20 by the time that I have implemented X and reaches 530 by the time I reach M. I can't simply factor it out as while I = 531 and V=535, MDCLXVI = 1560. That and eclipse sometimes says it can`t run and other times that it can.
Here`s the code
C int romanToInt(char *s) {
int n, k=0;
while(k<[MAX_LINE]) {
if(s[k]==’I’) {
n=n++
}
if(s[k]==’v’) {
n=n+5
}
if(s[k]==’X’) {
n=n+10
}
if(s[k]==’L’) {
n=n+50
}
if(s[k]==’C’) {
n=n+100
}
if(s[k]==’D’) {
n=n+500
}
if(s[k]==’M’) {
n=n+1000
}
return n;
}
Thanks for any help.
You initialize your loop counter, k, but not your accumulator, n. Initialize n=0; C assumes you know what you're doing so it doesn't automatically initialize ints to zero, like some OOP languages do. So, you could be starting with garbage, which throws off all your calculations. second: why n=n++? either user n+=1 or n++
also, a for loop would probably be better than a while loop because it forces you to initialize your counter variable (if you haven't already) and set a limit on the number of iterations, so hardly any chance of an infinite loop.
finally, instead of all those ifs, consider if/else if or a select/case.
oh, and i'm sure it's probably a typo but your return statement should be after the loop ends. You either forgot to add the extra brace before the return statement or I miscounted.