问题描述
float num = 10.0111
printf(%E,num);
输出:1.001110E + 001
但我想要= 1.00111E + 1
我尝试了什么:
我读了许多网站,有人写过C库中没有提供解决方案。
float num = 10.0111
printf("%E",num);
Output: 1.001110E+001
But I want = 1.00111E+1
What I have tried:
I read many website there were written that no hands on solution is available in C library.
推荐答案
指数应始终包含至少两位数。如果该值为零,则指数应为零。
The exponent shall always contain at least two digits. If the value is zero, the exponent shall be zero.
因此,唯一的解决方案是使用 sprintf()
打印到缓冲区,然后修改字符串。
示例:
So the only solution would be printing to a buffer using sprintf()
and modifying the string afterwards.
Example:
char buffer[64];
sprintf(buffer, "%E", num);
char *expPos = strchr(buffer, 'E');
int exp = atoi(expPos + 1);
sprintf(expPos + 1, "%+d", exp);
printf(buffer);
删除尾随零的版本在指数之前:
A version that removes also trailing zeroes before the exponent:
char buffer[64];
sprintf(buffer, "%E", num);
// Locate the exponent
char *expPos = strchr(buffer, 'E');
// Get the exponent value
int exp = atoi(expPos + 1);
// Skip trailing zeroes using pre-increment to start at the last digit.
// Afterwards expPos points to the last non-zero digit
do expPos--; while (expPos > buffer && *expPos == '0');
// Overwrite trailing zeroes and exponent with short exponent
sprintf(expPos + 1, "E%+d", exp);
printf(buffer);
[/ EDIT]
[/EDIT]
这篇关于如何格式化c程序中的%e格式说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!