C printf %e 如何控制 'e' 后的指数位数?

How to control the number of exponent digits after 'e' in C printf %e?

我想在C中控制'e'后的指数位数printf %e?

比如Cprintf("%e")结果2.35e+03,但是我想要2.35e+003,我需要3位指数,如何使用printf

代码:

#include<stdio.h>
int main()
{
    double x=34523423.52342353;
    printf("%.3g\n%.3e",x,x);
    return 0;
}

结果: http://codepad.org/dSLzQIrn

3.45e+07
3.452e+07

我要

3.45e+007
3.452e+007

但有趣的是,我在 Windows 中使用 MinGW 得到了正确的结果。

printf 格式化标签原型:

%[flags][width][.precision][length]specifier

The precision

... This gives ... the number of digits to appear after the radix character for a, A, e, E, f, and F conversions ... .

您正确使用了转换和精度说明符,不同之处在于 C 库函数的实现和不同系统上的环境。 precision 指定 '.' 之后的位数(点、句点等)。它不设置表示指数的字符数。它在 windows 上提供 3 digits 的事实只是 windows 指定格式的方式,而不是 C 标准库指定 printf 工作的方式。

需要比较源代码实现的不同,才能了解那段格式字符串所依赖的内容。 (它可能会归结为 windows v. linux/unix environments/locale/etc 的定义或指定方式上的一些模糊差异)

"...The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. ..." C11dr §7.21.6.1 8

所以 3.45e+07 是合规的(OP 不想要的)并且 3.45e+007 是不合规的(OP 想要的)。

由于 C 没有为代码提供改变指数位数的标准方法,因此代码只能自行解决。

各种编译器支持一些控件。

visual studio _set_output_format

为了好玩,下面是DIY代码

  double x = 34523423.52342353;
  //                    - 1 . xxx e - EEEE [=10=]
  #define ExpectedSize (1+1+1 +3 +1+1+ 4 + 1)
  char buf[ExpectedSize + 10];
  snprintf(buf, sizeof buf, "%.3e", x);
  char *e = strchr(buf, 'e');  // lucky 'e' not in "Infinity" nor "NaN"
  if (e) {
    e++;
    int expo = atoi(e);
    snprintf(e, sizeof buf - (e - buf), "%05d", expo);  // 5 more illustrative than 3
  }
  puts(buf);

  3.452e00007

另见 c++ how to get "one digit exponent" with printf

char *nexp(double x, int p, int n) // Number with p digits of precision, n digits of exponent.
{
 const int NN=12;
 static char s[NN][256];//(fvca)
 static int i=-1;
 int j,e;

 i=(++i)%NN; // Index of what s is to be used...
 sprintf(s[i],"%.*lE", p,x); // Number...
 for(j=0; s[i][j]; j++) if(s[i][j]=='E') break; // Find the 'E'...
 if(s[i][j]=='E') // Found!
  {
   e= atoi(s[i]+j+1);
   sprintf(s[i]+j+1, "%+0*d", n+1,e);
   return s[i];
  }
 else return "***";
}


// Best Regards, GGa
// G_G