如何控制在c的printf%E'E'后,指数的位数? [英] How to control the number of exponent digits after 'e' in C printf %e?
问题描述
我想控制的指数位在C'E'的printf%E
?
例如,C 的printf(%E)
结果 2.35e + 03
,但我想 2.35e + 003
,我需要指数的3个数字,我怎么使用的printf
?
code:
#包括LT&;&stdio.h中GT;
诠释的main()
{
双X = 34523423.52342353;
的printf(至3g \\ N%.3E,X,X);
返回0;
}
结果:
HTTP://$c$cpad.org/dSLzQIrn
3.45e + 07
3.452e + 07
我想
3.45e + 007
3.452e + 007
但有趣的是,我使用MinGW得到正确的结果在Windows中。
...该指数总是包含至少两个数字,仅作为有更多的位数作为必要重新present指数。......C11dr§7.21.6.18
块引用>所以
3.45e + 07
兼容(并不需要的东西OP)和3.45e + 007
不是标准(OP什么希望)。由于C没有提供code一种标准的方式来改变指数的位数,code是留给自生自灭。
各种编译器支持一些控制。
为了好玩,以下是DIY code
双X = 34523423.52342353;
// - 1。 XXXë - EEEE \\ 0
的#define ExpectedSize(1 + 1 + 1 + 3 + 1 + 1 + 4 + 1)
焦炭BUF [ExpectedSize + 10];
的snprintf(buf中,sizeof的BUF,%.3E,X);
字符* E =和strchr(BUF,'E'); //幸运的'e'不是无限,也不是南
如果(E){
Ë++;
INT博览会=的atoi(E);
的snprintf(E,sizeof的BUF - (E - BUF),%05D,世博会); // 5超过3说明
}
看跌期权(BUF); 3.452e00007另请参见 C ++如何获得"一个数字指数&QUOT ;与printf的
I want to control the number of exponent digits after 'e' in C
printf %e
?For example, C
printf("%e")
result2.35e+03
, but I want2.35e+003
, I need 3 digits of exponent, how do I useprintf
?Code:
#include<stdio.h> int main() { double x=34523423.52342353; printf("%.3g\n%.3e",x,x); return 0; }
Result: http://codepad.org/dSLzQIrn
3.45e+07 3.452e+07
I want
3.45e+007 3.452e+007
But interestingly, I got the right results in Windows with MinGW.
解决方案"...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
So
3.45e+07
is compliant (what OP does not want) and3.45e+007
is not compliant (what OP wants).As C does not provide a standard way for code to alter the number of exponent digits, code is left to fend for itself.
Various compilers support some control.
visual studio
_set_output_format
For fun, following is DIY code
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
Also see c++ how to get "one digit exponent" with printf
这篇关于如何控制在c的printf%E'E'后,指数的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!