前几日工作中有以科学计数法输出的需要,当时不知道库函数就有对应的格式,还自己写了一个,昨日经理说库函数自带,发现库函数的确支持。
linux执行man 3 printf,可以在手册中看到如下描述
e, E
The double argument is rounded and converted in the style [-]d.ddde±dd where there is one digit before the decimal-point character and the number of digits after it is equal to the precision; if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses the letter E (rather than e) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.
实验代码如下:
#include<stdio.h>
int main(){
printf("%.2E\n", 0.00001);
printf("%.2E\n", 1.00001);
printf("%.2E\n\n", 1234.234);
printf("%.2e\n", 0.00001);
printf("%.2e\n", 1.00001);
printf("%.2e\n", 1234.234);
return 0;
}
1.00E-05
1.00E+00
1.23E+03
1.00e-05
1.00e+00
1.23e+03
sprintf也支持科学计数法的格式化,用法和printf相同。
本文介绍了在Linux环境下,如何利用printf和sprintf函数进行科学计数法的格式化输出。通过man3printf查看手册,了解到'e'和'E'格式说明符可以用来转换double类型的数值为科学计数法,并可以通过精度控制小数点后的位数。示例代码展示了不同精度设置下的输出效果,演示了这两个函数的用法。
2340

被折叠的 条评论
为什么被折叠?



