1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
#include <string>
using namespace std;
const string UNITS[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
const string TENS[] = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
//======================================================================
string expandThousand( int n )
{
string result;
int hundreds, tens, units;
hundreds = n / 100;
n %= 100;
if ( n < 20 )
{
tens = 0;
units = n;
}
else
{
tens = n / 10;
units = n % 10;
}
if ( hundreds > 0 )
{
result += UNITS[hundreds] + " hundred";
if ( n > 0 ) result += " and ";
}
if ( tens > 0 )
{
result += TENS[tens];
if ( units > 0 ) result += "-";
}
if ( units > 0 )
{
result += UNITS[units];
}
return result;
}
//======================================================================
string expand( int n )
{
string result;
int millions, thousands, hundreds;
millions = n / 1000000;
n %= 1000000;
thousands = n / 1000;
n %= 1000;
hundreds = n / 100;
if ( millions > 0 )
{
result += expandThousand( millions ) + " million";
if ( thousands > 0 || n > 0 ) result += ( thousands + hundreds > 0 ? ", " : " and " );
}
if ( thousands > 0 )
{
result += expandThousand( thousands ) + " thousand";
if ( n > 0 ) result += ( hundreds > 0 ? ", " : " and " );
}
if ( n > 0 )
{
result += expandThousand( n );
}
return result;
}
//======================================================================
int main()
{
int n;
while ( true )
{
cout << "Enter a number between 1 and 999999999 (or 0 to finish): "; cin >> n;
if ( n <= 0 ) break;
cout << expand( n ) << endl;
}
}
//======================================================================
|