How to convert numbers into text?

后端 未结 8 860
执念已碎
执念已碎 2020-12-06 18:20

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

8条回答
  •  时光说笑
    2020-12-06 18:47

    #import 
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        int a, b, number, logNum, nThNum;
    
        NSLog(@"Please enter a valid integer: ");
        scanf("%d", &number); // read input as a decimal integer
    
        if (!number) // if zero or something other than a number is entered output zero
            NSLog(@"Zero");
        else if (number < 0) { // convert negatives to something that can be used
            number = -number;
            NSLog(@"(negative)"); // but output negative first then continue as usual
        }
    
        logNum = (log10(number) + 1); // find how many digits there are in the number
    
        for (int j=0; j < logNum; j++) {// loop based on number of digits
            a = pow(10,logNum-j);
            b = pow(10,logNum-1-j);
            nThNum = (number % a) / b;// find the nth digit in a number, in our case 1st
            switch (nThNum) {// output current digit that was found
                case 0:
                    NSLog(@"Zero");
                    break;
                case 1:
                    NSLog(@"One");
                    break;
                case 2:
                    NSLog(@"Two");
                    break;
                case 3:
                    NSLog(@"Three");
                    break;
                case 4:
                    NSLog(@"Four");
                    break;
                case 5:
                    NSLog(@"Five");
                    break;
                case 6:
                    NSLog(@"Six");
                    break;
                case 7:
                    NSLog(@"Seven");
                    break;
                case 8:
                    NSLog(@"Eight");
                    break;
                case 9:
                    NSLog(@"Nine");
                    break;
                default:
                    break;
            }
        }
    
        [pool drain];
        return 0;
    }
    

    Well, now that you've posted your code, your method will work great if you first reverse the number. So, you can just write a short routine to do that, then use your own code.

提交回复
热议问题