不使用c中的printf()打印浮动

时间:2016-02-21 22:08:06

标签: c floating-point printf

我正在尝试编写我的printf()函数。我想打印float / double值。这是我到目前为止所做的。

static void ft_float(va_list *ap, t_flag *flags)
{
  double myfloat;
  signed long int decipart;
  signed long int intpart;

  myfloat = va_arg(*ap, double);
  if (myfloat < 0)
  {
      ft_myputchar('-');
      myfloat *= -1;
  }
  intpart = (signed long int)myfloat;
  ft_putnbr(intpart);
  ft_myputchar('.');
  myfloat -= intpart;
  myfloat *= 1000000;  //upto 6 decimal points
  decipart = (signed long int)(myfloat + 0.5); //+0.5 to round of the value
  ft_putnbr(decipart);
}

正如您所看到的,显而易见的原因代码适用于1.424352,12313.1341414等浮点数。但小数点后的值小于1时则不行,例如1.004243,12313.0001341等。

1 个答案:

答案 0 :(得分:2)

函数printf可用于用零填充值。标志0将填充设置为0,宽度指定写入的最小字符数,如果需要,使用左侧的填充。

只需printf decipart,格式为:"%06ld"