打印浮点数时,如何更精确地打印小数位?
When printing a float, how can you print decimal places more precisely?
我对编码还很陌生,遇到了一个非常基本的问题。我编写了一个程序来执行基本方程式,printf
结果:
#include <stdio.h>
int main (void)
{
float f = (380 / 3);
printf("%f\n", f);
}
然而,我得到的结果是126.000000
。如何让我的程序更精确地打印出小数位?
How can I make my program print out the decimal places more precisely?
第 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
我对编码还很陌生,遇到了一个非常基本的问题。我编写了一个程序来执行基本方程式,printf
结果:
#include <stdio.h>
int main (void)
{
float f = (380 / 3);
printf("%f\n", f);
}
然而,我得到的结果是126.000000
。如何让我的程序更精确地打印出小数位?
How can I make my program print out the decimal places more precisely?
第 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