藍橋杯——第八週校內練習總結(羅馬數字與十進位制數互轉)
阿新 • • 發佈:2019-01-12
先給出羅馬數字與十進位制對應的表:
I V X L C D M
1 5 10 50 100 500 1000
特別的,要首先考慮這幾個:
IV 是4,4不是IIII;同理9是IX;40是XL;90XC;400CD;900CM。
所以先給出十進位制int轉羅馬數字的程式碼:
int num[7] = { 1, 5,10,50,100,500,1000 }; char str[7] = { 'I','V','X','L','C','D','M' }; void changeTwo(int x) { int q, b, g; q = x / 1000; for (int i = 0; i < q; i++) cout << 'M'; x = x % 1000; if (x >= 900) { cout << "CM"; x = x - 900; } else if (x >= 500) { cout << 'D'; x = x - 500; } else if (x >= 400) { cout << "CD"; x = x - 400; } b = x / 100; x = x % 100; for (int i = 0; i < b; i++) cout << 'C'; if (x >= 90) { cout << "XC"; x = x - 90; } else if (x >= 50) { cout << 'L'; x = x - 50; } else if (x >= 40) { cout << "XL"; x = x - 40; } g = x / 10; x = x % 10; for (int i = 0; i < g; i++) cout << 'X'; if (x >= 9) { cout << "IX"; x = x - 9; } else if (x >= 5) { cout << 'V'; x = x - 5; } else if (x == 4) { cout << "IV"; x = x - 4; } for (int i = 0; i < x; i++) cout << 'I'; cout << endl; }
接著是羅馬數字轉十進位制的演算法,這個比十進位制轉羅馬要複雜,需要更加註意:
傳入一個string型別的pL返回一個相對應的int值。
int num[7] = { 1, 5,10,50,100,500,1000 }; char str[7] = { 'I','V','X','L','C','D','M' }; int change(string pL) { int c = 0; int j, k; int a[100]; int sum = 0; for (j = 0; j<100; j++) { a[j] = -1; } for (j = 0; pL[j] != '\0'; j++) { for (k = 0; k<100; k++) { if (pL[j] == str[k]) { a[j] = num[k]; break; } } } for (j = 0; j<100; j++) { if (a[j] == -1) break; if (a[j]<a[j + 1]) { sum += a[j + 1] - a[j]; j++; continue; } else sum += a[j]; } return sum; }