I need help in this my Roman numeral Code (C language)
Well, I created this code as a form of draft pro project that I have in which it turns certain words into decimal values, but I did with Roman numerals because it's easier that way for now, but there's a problem, every time I do XL
that should give the value of 40
, it's calculated as 60
, and when I do LX
that should give 60
gives -40
, Probably it's a logic problem, but I'm not being able to find where I'm going wrong in that code, thank you right now.
PS: the rest works well, IV
gives 4
right and IX
gives 9
normal too, for example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cot2dec(char s[100]){
int i, c = 0, valor;
char s2[100];
for(i=0; i<strlen(s); i++){
if(s[i] > s[i+1]){
switch(s[i]){
case 'I':
valor=1;
break;
case 'V':
valor=5;
break;
case 'X':
valor=10;
break;
case 'L':
valor=50;
break;
default:
printf("insira um valor valido.");
break;
}
c+=valor;
} else if(s[i] < s[i+1]){
switch(s[i]){
case 'I':
valor=1;
break;
case 'V':
valor=5;
break;
case 'X':
valor=10;
break;
case 'L':
valor=50;
break;
default:
printf("insira um valor valido.");
break;
}
c-=valor;
} else if(s[i] == s[i+1]){
switch(s[i]){
case 'I':
valor=1;
break;
case 'V':
valor=5;
break;
case 'X':
valor=10;
break;
case 'L':
valor=50;
break;
default:
printf("insira um valor valido.");
break;
}
c+=valor;
}
}
return c;
}
int main() {
char cad[100];
int cotinter;
printf("Insira um algarismo romano: ");
scanf("%s", &cad);
cotinter = cot2dec(cad);
printf("O valor decimal de %s e %d", cad, cotinter);
return 0;
}
1 answers
The Code problem is in these lines:
if(s[i] > s[i+1])
if(s[i] < s[i+1])
You are comparing char, and this comparison is done by the value of the ASCII table. For example The X is worth 10 in Roman numeral, while L is worth 50, however when comparing the two X is greater than L, because in the ASCII table X = 88, L = 76. And you want X to be smaller.
int convertValor(char s[100]){
int valS[100];
int i, j, c = 0, valor;
for(j=0; j<strlen(s); j++){
if(s[j] == 'I'){
valS[j] = 1;
}else if(s[j] == 'V'){
valS[j] = 5;
}
else if(s[j] == 'X'){
valS[j] = 10;
}
else if(s[j] == 'L'){
valS[j] = 50;
}
}
valS[strlen(s)] = 0;
for(i=0; i<strlen(s); i++){
if(valS[i] > valS[i+1]){
printf("Valor MAIOR %d\n",valS[i]);
switch(valS[i]){
case 1:
valor=1;
break;
case 5:
valor=5;
break;
case 10:
valor=10;
break;
case 50:
valor=50;
break;
default:
printf("insira um valor valido.");
break;
}
c+=valor;
} else if(valS[i] < valS[i+1]){
printf("Valor MENOR %d\n",valS[i]);
switch(valS[i]){
case 1:
valor=1;
break;
case 5:
valor=5;
break;
case 10:
valor=10;
break;
case 50:
valor=50;
break;
default:
printf("insira um valor valido.");
break;
}
c -=valor;
} else if(valS[i] == valS[i+1]){
switch(valS[i]){
case 1:
valor=1;
break;
case 5:
valor=5;
break;
case 10:
valor=10;
break;
case 50:
valor=50;
break;
default:
printf("insira um valor valido.");
break;
}
c+=valor;
}
}
return c;
}