我对编码很陌生,但遇到了一个非常基本的问题。我已经编写了一个执行基本方程式和printf
结果的程序:
#include <stdio.h>
int main (void)
{
float f = (380 / 3);
printf("%f\n", f);
}
但是,我得到的结果是126.000000
。如何使我的程序更精确地打印出小数位?
如何使我的程序更精确地打印出小数位?
步骤1,使用浮点FP数学,而不是整数数学。
// float f = (380 / 3); // int math
// float f = 380.0f / 3.0f; // float math
double f = 380.0 / 3.0; // double math
步骤2:指定的精度应超过默认值6。
int prec = 7;
printf("%.*f\n", pre, f);
...或更好,使用指数表示法
printf("%.*e\n", FLT_DECIMAL_DIG, f);
....甚至十六进制。
printf("%a\n", f);
#include <float.h>
#include <stdio.h>
int main(void) {
double f = 380.0 / 3.0;
int prec = 7;
printf("%.*f\n", prec, f);
printf("%.*e\n", DBL_DECIMAL_DIG, f);
printf("%a\n", f);
}
输出
126.6666667
1.26666666666666671e+02
0x1.faaaaaaaaaaabp+6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句