Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

ios - How to convert numbers into text?

I have been learning Objective-C with the Kochan book and I can't figure out how to do this exercise program. Only odd numbered exercises are listed online and this one is even. The exercise is to convert numbers into words. So, if "932" was entered, the program should return: "nine three two"

I used a do, while loop but the words came out backwards, as in "two three nine". Can anyone suggest a technique that works for this?

int number, digit;


NSLog(@"Type in your integer.");
scanf("%i", &number);


 do
 {
     digit = number % 10;

     if (digit == 0)
         NSLog(@"zero");
     if (digit == 1)
         NSLog(@"one");
     if (digit == 2)
         NSLog(@"two");
     if (digit == 3)
         NSLog(@"three");
     if (digit == 4)
         NSLog(@"four");
     if (digit == 5)
         NSLog(@"five");
     if (digit == 6)
         NSLog(@"six");
     if (digit == 7)
         NSLog(@"seven");
     if (digit == 8)
         NSLog(@"eight");
     if (digit == 9)
         NSLog(@"nine");

     number /= 10;
 }
while (number != 0);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This isn't exactly what you want, but for your consideration:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterSpellOutStyle];

NSString *s = [f stringFromNumber:[NSNumber numberWithInt:932]];
NSLog(@"%@", s);
[f release];

This will log:

nine hundred and thirty-two

Again, it's not the "nine three two" you want, but it's also nice and short. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...