在不使用Printf或任何功能的情况下用C打印int [英] Print an int in C without Printf or any functions

查看:151
本文介绍了在不使用Printf或任何功能的情况下用C打印int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分配,需要在C中打印整数而不使用printf,putchar等.不允许包含任何头文件.除了我写的任何东西,没有函数调用.我有一个正在使用的函数my_char(可能是错误的),但它会打印出一个字符.我目前有以下代码,它将代码向后打印.没有寻找答案.只是在寻找一些方向,一些帮助,也许我在看它是完全错误的.

void my_int(int num)
{   
  unsigned int i;    
  unsigned int j;

  char c;

  if (num < 0)    
    {
      my_char('-');
      num = -num;
    }

  do    
    {
      j = num % 10;
      c = j + '0';
      my_char(c);
      num = num/10;
    }while(num >0);
}

解决方案

与其在循环中调用my_char(),不如将字符打印"到缓冲区,然后反向循环通过缓冲区以将其打印出来. >

结果是您不能使用数组.在这种情况下,您可以通过循环算出最大功率10(即log10).然后使用它从第一位开始向后工作.

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;
}

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 I wrote. I have one function my_char I am using (maybe its wrong) but it prints out a character. I currently have the following code which is printing the number out backwards. Not looking for an answer. Just looking for some direction, some help, maybe I'm looking at it completely wrong.

void my_int(int num)
{   
  unsigned int i;    
  unsigned int j;

  char c;

  if (num < 0)    
    {
      my_char('-');
      num = -num;
    }

  do    
    {
      j = num % 10;
      c = j + '0';
      my_char(c);
      num = num/10;
    }while(num >0);
}

解决方案

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;
}

这篇关于在不使用Printf或任何功能的情况下用C打印int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆