用Visual Studio測試正常,但用測資或送出解答卻顯示記憶體區段錯誤
#include<stdio.h>
#include<string.h>
#define MaxRome 50
#define MaxNum 4
struct RomeNum{
char Rome[7];
int Num[7];
};
int RomeToNum(struct RomeNum, char*);//Transfer Romestrings into number
char* NumToRome(struct RomeNum, int);
int main() {
char A[MaxRome] = { 0 }, B[MaxRome] = { 0 };
struct RomeNum RN= { { 'I', 'V', 'X', 'L', 'C', 'D', 'M'},{1, 5, 10, 50, 100, 500, 1000 } };
while (scanf("%s %s", A, B) != EOF ) {
if (A[0] == '#') break;
int sum_a, sum_b, AnsNum;
char AnsRome[MaxRome] = { 0 };
sum_a = RomeToNum(RN, A);
sum_b = RomeToNum(RN, B);
AnsNum = sum_a - sum_b;
if (sum_a > sum_b)
AnsNum = sum_a - sum_b;
else
AnsNum = sum_b - sum_a;
strcpy(AnsRome, NumToRome(RN, AnsNum));
if (AnsNum == 0)
printf("ZERO\n");
else
printf("%s\n", AnsRome);
}
return 0;
}
int RomeToNum(struct RomeNum RN, char* RomeInput) {
int n, j, k[MaxRome] = { 0 };
int Len = strlen(RomeInput), sum = 0;
//To find if there is a bigger Rome character at right side(n+1),
//then mark a minus sign at the character of n index.
//At the same time, summarize the Num of RomeNumber.
for (n = 0; n < Len - 1; n++) {
for (j = 0; j < strlen(RN.Rome); j++) {
if (RomeInput[n] == RN.Rome[j])
k[n] = j;//k represent the index of the character in the RN
if (RomeInput[n + 1] == RN.Rome[j])
k[n + 1] = j;
}
if (k[n + 1] > k[n]) {
sum += -RN.Num[k[n]];
}
else
sum += RN.Num[k[n]];
}
//Add the last one of k;
sum += RN.Num[k[n]];
return sum;
}
char* NumToRome(struct RomeNum RN, int NumInput) {
int Num[MaxNum] = { 0 }, i = 1, j = 0, counter = 0;
char Rome[MaxRome] = { 0 };
if (NumInput >= 4000) return NULL;
while (NumInput > 0) {
Num[MaxNum-i] = NumInput % 10;
NumInput /= 10;
i++;
}
for (i = 0; i < MaxNum; i++) {
if (Num[i] <= 3) {
for (j = 0; j < Num[i]; j++) { //If Num[i]= 0 then jump out of loop
Rome[counter] = RN.Rome[6 - 2 * i];//2*((4-1)-i)
counter++;
}
}
if (Num[i] == 4) {
Rome[counter] = RN.Rome[6 - 2 * i];
counter++;
Rome[counter] = RN.Rome[7 - 2 * i];//2*((4-1)-i)+1
counter++;
}
if (Num[i] >= 5 && Num[i] < 9) {
Rome[counter] = RN.Rome[7 - 2 * i];
counter++;
for (j = 0; j < Num[i]-5; j++) { //If Num[i]-5= 0 then jump out of loop
Rome[counter] = RN.Rome[6 - 2 * i];
counter++;
}
}
if (Num[i] == 9) {
Rome[counter] = RN.Rome[6 - 2 * i];
counter++;
Rome[counter] = RN.Rome[8 - 2 * i];//2*((4-1)-i)+2
counter++;
}
}
return Rome;
}