Re: Converting Numbers to Words in English by recursion.
- From: Steve O'Hara-Smith <steveo@xxxxxxxxxx>
- Date: Sat, 10 Mar 2007 11:08:03 +0000
On 9 Mar 2007 20:03:09 -0800
jedale@xxxxxxxxx wrote:
I am trying to convert numbers to there corresponding words but it
only works for numbers under 1,000 but need it to work for 1 billion.
It doesn't even work for numbers between 10 and 20 - you need to
special case those - and the handling above 1000 is completely off. Try
the code below (and if you switch to unsigned long long instead of int and
extend the places and place_sizes lists and the loop you can go much higher)
With regard to testing which has occupied most of this thread I
suggest a middle ground of making a test script that excercises the program
testing for expected results on spot checks in the range 0-9, 10-20, 20-100,
100-1000, 1000-100000, and so forth.
I didn't bother with a script I jyst
hand spot checked the results - but then I don't intend to keep this code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/* Prototype */
void print_num(int num);
char *smallnum[] = {
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sizteen", "seventeen",
"eighteen", "nineteen"
};
char *tens[] = {
"twenty", "thirty", "fourty", "fifty", "sixty",
"seventy", "eighty", "ninety"};
char *places[] = {"thousand", "million", "billion"};
int place_sizes[] = {1000, 1000000, 1000000000};
int main(int arcg, char **argv)
{
int num = atoi(argv[1]);
printf("%d\n", num); /* Print that number */
print_num(num);
}
/* Print out the number sequence */
void print_num(int num)
{
int i;
if (num < 20)
{
printf("%s ", smallnum[num]);
}
else if (num < 100)
{
printf("%s ", tens[num/10 - 2]);
if (num % 10)
print_num(num%10);
}
else if(num < 1000)
{
print_num(num/100);
printf("hundred ");
if (num % 100)
print_num(num%100);
}
else
{
for (i = 2; i >= 0; i--)
{
if (num / place_sizes[i])
{
print_num(num / place_sizes[i]);
printf ("%s ", places[i]);
num = num % place_sizes[i];
}
}
if (num)
print_num(num);
}
}
--
C:>WIN | Directable Mirror Arrays
The computer obeys and wins. | A better way to focus the sun
You lose and Bill collects. | licences available see
| http://www.sohara.org/
.
- References:
- Converting Numbers to Words in English by recursion.
- From: jedale
- Converting Numbers to Words in English by recursion.
- Prev by Date: Re: how to test this piece of C code
- Next by Date: Re: how to test this piece of C code
- Previous by thread: Re: Converting Numbers to Words in English by recursion.
- Next by thread: Re: Converting Numbers to Words in English by recursion.
- Index(es):
Relevant Pages
|