SOGO論壇

標題: 請問數字跟羅馬字互換~~幾行看不懂~~求解! [列印本頁]

作者: 劍君13恨    時間: 2016-11-20 16:46:01     標題: 請問數字跟羅馬字互換~~幾行看不懂~~求解!

#include<iostream>
using namespace std;

int r2a( char ch )
{
  switch( ch ) {
    case 'I': return 1;
    case 'V': return 5;
    case 'X': return 10;
    case 'L': return 50;
    case 'C': return 100;
    case 'D': return 500;
    case 'M': return 1000;
    default: return 0;
  }
}

char a2r( int n )
{
  switch( n ) {
    case 1: return 'I';
    case 5: return 'V';
    case 10: return 'X';
    case 50: return 'L';
    case 100: return 'C';
    case 500: return 'D';
    case 1000: return 'M';
    default: return '\0';
  }
}

void roman( int m ){
  int remain, count,i;
  char ch;
  int a[] = {1,5,10,50,100,500,1000};
  remain = m;
  if( m==0 ) cout << "ZERO" ;
  i = 7;
  while(remain && i>0){
    i--;
    count = remain / a;
    ch = a2r(a);
    for( int j=0;j<count;j++) cout << ch;
    remain -= count * a;
    if ( remain < a- (i==0 ? 0 : a[i-(i%2?1:2)]) ) continue;
    if( remain >= a - 1) {
     cout << 'I' << ch ;
     remain -= (a-1);
    }else if( remain >= a-10){
     cout << 'X' << ch ;
     remain -= (a-10);
    }else if( remain >= a -100){
     cout << 'C' << ch ;
     remain -= (a-100);

    }
  }
}

int main()
{
  int r;
  cout << "Input a number(I,V,X,L,C,D,M來代表1,5,10,50,100,500,1000):";
  cin >> r;
  roman(r);
  return 0;
}


有大哥大姐可以簡單解釋紅色字的用途嗎?  




歡迎光臨 SOGO論壇 (https://oursogo.com/) Powered by OURSOGO.COM