[英]How to control the number of exponent digits after 'e' in C printf %e?
我想控制 C printf %e
“e”之后的指數位數?
例如,C printf("%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 得到了正確的結果。
“...指數始終包含至少兩位數字,並且僅包含表示指數所需的更多數字。...” C11dr §7.21.6.1 8
所以3.45e+07
是合規的(OP 不想要的)而3.45e+007
不合規(OP 想要的)。
由於 C 沒有為代碼提供改變指數位數的標准方法,因此代碼需要自己解決。
各種編譯器支持一些控制。
為了好玩,以下是DIY代碼
double x = 34523423.52342353;
// - 1 . xxx e - EEEE \0
#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
printf
格式標簽原型:
%[flags][width][.precision][length]specifier
精度
... 這給出了 ... 出現在 a、A、e、E、f 和 F 轉換的基數字符之后的位數...。
您正確使用了轉換和精度說明符,區別在於 C 庫函數的實現和不同系統上的環境。 precision
指定'.'
后的位數'.'
(點、句點等)。 它不設置表示冪的字符數。 它在 windows 上提供3 digits
的事實只是 windows 指定格式的方式,而不是 C 標准庫指定printf
將工作的方式。
需要比較源實現的不同之處,以了解該格式字符串依賴於什么。 (它可能歸結為 windows v. linux/unix 環境/語言環境/等的定義或指定方式的一些模糊差異)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.