%c specifier char limit capped in C,如何避免这种情况?

%c specifier char limit capped in C, how to avoid that?

当我尝试输出十六进制数的小数部分时,我 运行 遇到了问题。

基本上,使用以下代码:

float d2h(float decimal, float fraction) {
  int i = 0;
  char hex[17] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                   'A', 'B', 'C', 'D', 'E', 'F', '[=10=]' };
  int temp = (int) decimal;
  int j;
  for (j = 0; j < 60; j++) {
    fraction = fraction - (int) fraction;
    displayFractionHex[j] = hex[(int) (fraction * 16)];
    fraction *= 16;
  }
  for (i = sizeof(displayDecimalHex) - 1; i >= 0; i--) {
    displayDecimalHex[i] = hex[temp % 16];
    temp /= 16;
  }
  int n;
  if ((n = strspn(displayDecimalHex, "0")) != 0
      && displayDecimalHex[n] != '[=10=]')        // strspn() - Reference
    printf("%s", &displayDecimalHex[n]);
  printf(".");
  for (i = 0; i < 20; i++) {
    printf("%c", displayFractionHex[i]);
  }
}

我得到了输出222.74BC0000000000000000,我显然希望十六进制数的小数部分显示更多的字符。

但是,当我尝试将最后一个 printf 语句更改为 %s 说明符而不是 %c 时,我的程序崩溃了。

我曾尝试将阵列复制到另一个阵列,不幸的是没有用。

OP 评论:

expected output is something along the lines of 222.74bc6a7ef9d...

典型的 float222.74BC000000... 一样大约有 24 位二进制精度。

为了更高精度的使用,double.

printf("%a\n%a\n", (float) 546.456, 546.456);为例,看看区别。

0x1.113a5ep+9
0x1.113a5e353f7cfp+9

明确地说,"thus the decimal float is 546 and the fractional float is 0.456" 是不正确的。 d2h(float decimal) 的输入是 不是 546.456,但最接近它的可表示 float 恰好是 546.4559936523437500... float 在十六进制 FP 中正好是 222.74BC