int romanToInt(char* s) {
int len = strlen(s);
int i = 0;
int sum = 0;
int* flag = (int*)malloc(len * sizeof(int));
if (flag == NULL) { // <---- malloc 不一定会申请成功
printf("内存申请失败\n");
return 0;
}
for (i = 0; i < len; i++) {
switch (s[i]) {
case 'I':flag[i] = 1; break;
case 'V': flag[i] = 5; break;
case 'X': flag[i] = 10; break;
case 'L': flag[i] = 50; break;
case 'C': flag[i] = 100; break;
case 'D': flag[i] = 500; break;
case 'M': flag[i] = 1000; break;
}
}
for (i = 0; i < len - 1; i++) {
if (flag[i] >= flag[i + 1]) { // <--- 正确条件 >=
flag[i] = flag[i];
} else {
flag[i] = -flag[i];
}
}
for (i = 0; i < len; i++) {
sum += flag[i];
}
if (flag != NULL) { // <--- 无论是否为NULL 都必须检查
free(flag); // <--- malloc后记得释放内存
flag = NULL; // <--- 避免指针被二次引用,虽然这里用不到,但要养成好习惯
}
return sum;
}
void test();
int main() {
// 罗马数字转阿拉伯数字
char buff[10] = { 0 };
loop:
printf("请输入罗马数字:");
scanf_s("%s",buff, 10);
printf("转换后为:%d\n", romanToInt(buff));
goto loop;
return 0;
}
typedef struct _roma_test {
char str[15];
int num;
}ROMATEST;
void test() {
ROMATEST list[] = {
{"I",1},
{"II",2},
{"III",3},
{"IV",4},
{"V",5},
{"VI",6},
{"VII",7},
{"VIII",8},
{"IX",9},
{"X",10},
{"XI",11},
{"XII",12},
{"XIII",13},
{"XIV",14},
{"XV",15},
{"XVI",16},
{"XVII",17},
{"XVIII",18},
{"XIX",19},
{"XX",20},
{"XXX",30},
{"XL",40},
{"L",50},
{"LX",60},
{"LXX",70},
{"LXXX",80},
{"XC",90},
{"XCIX",99},
{"C",100},
{"CI",101},
{"CII",102},
{"CXCIX",199},
{"CC",200},
{"CCC",300},
{"CD",400},
{"D",500},
{"DC",600},
{"DCCC",800},
{"CM",900},
{"M",1000},
{"MCD",1400},
{"MCDXXXVII",1437},
{"MD",1500},
{"MDCCC",1800},
{"MDCCCLXXX",1880},
{"MCM",1900},
{"MM",2000},
{"MMM",3000},
{"MMMCCCXXXIII",3333},
{"MMMCMXCIX",3999}
};
bool all_ok = true;
for (int i = 0; i < _countof(list);i++) {
int mynum = romanToInt(list[i].str);
if (list[i].num != mynum) {
printf("发现该算法与正确的数存在差异! 正确结果:%s %d ,算法的结果是:%d\n", list[i].str, list[i].num, mynum);
all_ok = false;
break;
}
}
printf("测试完毕,结果是:%s", all_ok?"算法通过测试,全部正确":"算法有误");
}