Print an int in C without Printf or any functions

后端 未结 3 1259
闹比i
闹比i 2021-01-19 03:37

I have an assignment where I need to print an integer in C without using printf, putchar, etc. No header files allowed to be included. No function calls except for anything

相关标签:
3条回答
  • 2021-01-19 04:19

    One option might be to do this recursively, so the number gets printed out in the right order.

    In this case, instead of a do/while loop, you'd have a construction more like this, with a base case of num=0.

    if(num==0)
        return;
    
    j = num % 10;
    c = j + '0';
    my_int(num/10);
    my_char(c);
    

    Edit: Noticed that you aren't allowed to use recursion. It's a bit ugly, but you could check for the digits in the number, and then loop backwards across the number.

    To find the number of digits,

    int digitDivide = 1;
    int tempNum = num;
    while(tempNum>0){
        tempNum= tempNum/10;
        digitDivide=digitDivide*10;
    }
    

    and then use that to loop through the number as follows:

    digitDivide = digitDivide/10;
    while(digitDivide>0){
        tempNum = (num/digitDivide)%10;
        c = j + '0';
        my_char(c);
        digitDivide=digitDivide/10;
    }
    
    0 讨论(0)
  • 2021-01-19 04:20

    Instead of calling my_char() in the loop instead "print" the chars to a buffer and then loop through the buffer in reverse to print it out.

    Turns out you can't use arrays. In which case you can figure out the max power of 10 (ie log10) with the loop. Then use this to work backwards from the first digit.

    unsigned int findMaxPowOf10(unsigned int num) {
        unsigned int rval = 1;
        while(num) {
            rval *= 10;
            num /= 10;
        }
        return rval;
    }
    
    unsigned int pow10 = findMaxPowOf10(num);
    
    while(pow10) {
        unsigned int digit = num / pow10;
        my_char(digit + '0');
        num -= digit * pow10;
        pow10 /= 10;
    }
    
    0 讨论(0)
  • 2021-01-19 04:37

    You can convert an int to char * , char * and display this char* :

    char        *put_int(int nb)
    {
     char       *str;
    
     str = malloc(sizeof(char) * 4);
     if (str == NULL)
       return (0);
     str[0] = (nb / 100) + '0';
     str[1] = ((nb - ((nb / 100 * 100 )) / 10) + '0');
     str[2] = ((nb % 10) + '0');
     return (str);
    }
    
    void        put_str(char *str)
    {
     while (*str)
       write(1, str++,1);
    }
    
    int main(void)
    {
     put_str(put_int(42));
     return (0);
    }
    
    0 讨论(0)
提交回复
热议问题