C - Issue converting a user generated number into words

后端 未结 3 2021
予麋鹿
予麋鹿 2021-01-15 16:56

So I\'ve been working my way through Kochan\'s Programming in C and I\'ve hit a snag on one of the questions which reads as follows:

\"Write a program that takes an

3条回答
  •  别那么骄傲
    2021-01-15 17:36

    In your reverseNumber function you have not initialized Rev. Make Rev=0

    int reverseNumber (int y)
    {
        int cnt, Rev=0;
        cnt = digitCount(y);  //returns number of digits
    
        printf("Digit count %d\n", cnt);
        while (cnt != 0) {
            Rev = Rev * 10 + y % 10;
            y = y / 10;
            cnt--;
        }
    
        return Rev;
    }
    

    In main in the do while loop use a temporary variable since you are overwriting numberValue with numberValue % 10. But the most ironic part in your program (where you complicated everything for yourself) is that there is no need to reverse the number at all. See the code here

    1. In the way user entered - http://ideone.com/pORaP2
    2. In reverse order - http://ideone.com/5GS8al

    When you find modulo you get the number in the reverse order itself. Suppose you entered 234

    1. First step 234%10 gives 4 prints four. And then makes 234 to 23

    2. Second step 23%10 gives 3 prints three. And then makes 23 to 2

    and then finally prints two.

提交回复
热议问题